Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(sandbox) (#2301)

nullptr-error5df788dc7776
diff --git a/.air.toml b/.air.toml
index a19ce7202..73f8c3219 100644
--- a/.air.toml
+++ b/.air.toml
@@ -44,3 +44,6 @@ tmp_dir = "tmp"
clear_on_rebuild = false
keep_scroll = true
+[cmd]
+ # 重启前执行的清理命令
+ stop = "sudo lsof -t -i :18080 | xargs -r sudo kill -9"
\ No newline at end of file
diff --git a/.env.example b/.env.example
index ccbb1f27b..582940154 100644
--- a/.env.example
+++ b/.env.example
@@ -569,12 +569,69 @@ SYSTEM_AES_KEY=weknora-system-aes-key-32bytes!!
# #####################################################################
# ========== G1. Agent Skills Sandbox ==========
-# Sandbox 模式:docker(默认)/ local / disabled。
+# 以下 WEKNORA_SANDBOX_* 均为「部署级默认值」。工作区可在「设置 → 沙箱后端」中维护
+# 多份具名配置(同一后端类型也可以有多份,例如两个 E2B 账号),智能体在编辑弹窗的
+# 「能力扩展 → 沙箱后端」里各自选择其一;未选择的智能体回落到这里的默认值。
+# 具名配置是自包含的:不会回退到这里的值,端点/密钥/域名/模板必须在配置里填全。
+#
+# Sandbox 模式:docker(默认)/ local / cube / e2b / disabled。
+# docker - Docker 容器隔离(一次性容器)
+# local - 本地进程 + 白名单(一次性执行)
+# cube - Tencent CubeSandbox MicroVM(会话级持久,每 Session 独占一个沙箱)
+# e2b - E2B 云端 MicroVM(会话级持久;依赖第三方 SDK go-e2b)
+# disabled - 关闭本实例全部沙箱能力(含工作区具名配置;部署级总闸)
WEKNORA_SANDBOX_MODE=docker
# 脚本执行超时(秒,默认 60)。
WEKNORA_SANDBOX_TIMEOUT=60
# Sandbox Docker 镜像(默认 wechatopenai/weknora-sandbox:latest)。
# WEKNORA_SANDBOX_DOCKER_IMAGE=wechatopenai/weknora-sandbox:latest
+
+# 是否允许租户沙箱配置使用 loopback / 私网地址(127.0.0.1、RFC1918)。
+# 自建 Cube/E2B 必填 true;公网 SaaS _endpoint 保持 false(默认)。
+# 无论何种取值,169.254.0.0/16(云 metadata)始终禁止。
+# WEKNORA_SANDBOX_ALLOW_PRIVATE_ENDPOINTS=false
+
+# ---------- 会话级沙箱通用配置(cube / e2b 生效) ----------
+# 工作区使用具名 Cube/E2B 配置,或部署默认 mode=cube/e2b 时,需要 REDIS_ADDR
+# 以在多实例间共享 session→sandbox binding。仅单机 dev 可:
+# WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true
+
+# 会话→沙箱绑定的 Redis key 命名空间。不设置时复用 WEKNORA_REDIS_NAMESPACE,
+# 再退回到 "weknora"。
+# WEKNORA_SANDBOX_REDIS_NAMESPACE=weknora
+
+# ---------- CubeSandbox 专用配置(仅当 WEKNORA_SANDBOX_MODE=cube 时生效) ----------
+# CubeAPI 端点,用于创建/销毁沙箱。参考 Cube 部署中的 CUBE_API_BIND。
+WEKNORA_SANDBOX_CUBE_API_URL=http://127.0.0.1:33000
+# CubeProxy 端点,用于通过 Host 头路由到 envd 执行脚本/上传文件。
+# 参考 Cube 部署中的 CUBE_PROXY_HTTP_PORT(默认 80)。
+WEKNORA_SANDBOX_CUBE_PROXY_URL=http://127.0.0.1:80
+# CubeProxy 使用的沙箱路由域名(参考 CUBE_API_SANDBOX_DOMAIN)。
+WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN=cube.app
+# X-API-Key 认证头;本地部署一般无鉴权,保持为空即可。
+# WEKNORA_SANDBOX_CUBE_API_KEY=
+# 默认模板 ID(在 CubeMaster 中注册的模板)。
+WEKNORA_SANDBOX_CUBE_TEMPLATE=tpl-54becd2c417742e6a190bd3e
+# Cube 端沙箱 TTL(秒),到期后 Cube 侧 pause(非销毁)。默认 1800(30 分钟)。
+WEKNORA_SANDBOX_CUBE_SANDBOX_TTL=1800
+# 单次 HTTP 请求的超时(秒);不影响脚本执行本身的超时。默认 30。
+# WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT=30
+
+# ---------- E2B 专用配置(仅当 WEKNORA_SANDBOX_MODE=e2b 时生效) ----------
+# 说明:E2B 后端依赖第三方 SDK go-e2b。
+# E2B API Key(必填),从 https://e2b.dev/dashboard 获取。
+# WEKNORA_SANDBOX_E2B_API_KEY=
+# E2B 控制面地址,默认 https://api.e2b.app(自建部署可覆盖)。
+# WEKNORA_SANDBOX_E2B_API_URL=https://api.e2b.app
+# envd 路由域名,默认 e2b.app(自建部署可覆盖)。
+# WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN=e2b.app
+# 模板 ID / 别名(在 E2B 上先构建,见 https://e2b.dev/docs/template)。
+# WEKNORA_SANDBOX_E2B_TEMPLATE=base
+# E2B 端 idle timeout(秒),默认 300;超过后 E2B 自动paused。
+# WEKNORA_SANDBOX_E2B_SANDBOX_TTL=300
+# 单次 HTTP 请求的超时(秒),默认 30。
+# WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT=30
+
# 自定义 Skills 目录(挂载后指定,免重建镜像)。
# WEKNORA_SKILLS_DIR=
# 智能体大模型调用默认超时(秒,默认 120;复杂推理调大如 300/600)。
diff --git a/docker-compose.yml b/docker-compose.yml
index 1ecb490b9..c605e2962 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -316,6 +316,14 @@ services:
- WEKNORA_SANDBOX_MODE=${WEKNORA_SANDBOX_MODE:-docker}
- WEKNORA_SANDBOX_TIMEOUT=${WEKNORA_SANDBOX_TIMEOUT:-60}
- WEKNORA_SANDBOX_DOCKER_IMAGE=${WEKNORA_SANDBOX_DOCKER_IMAGE:-wechatopenai/weknora-sandbox:${WEKNORA_VERSION:-latest}}
+ - WEKNORA_SANDBOX_REDIS_NAMESPACE=${WEKNORA_SANDBOX_REDIS_NAMESPACE:-}
+ # E2B (experimental; leave empty unless WEKNORA_SANDBOX_MODE=e2b).
+ - WEKNORA_SANDBOX_E2B_API_KEY=${WEKNORA_SANDBOX_E2B_API_KEY:-}
+ - WEKNORA_SANDBOX_E2B_API_URL=${WEKNORA_SANDBOX_E2B_API_URL:-}
+ - WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN=${WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN:-}
+ - WEKNORA_SANDBOX_E2B_TEMPLATE=${WEKNORA_SANDBOX_E2B_TEMPLATE:-}
+ - WEKNORA_SANDBOX_E2B_SANDBOX_TTL=${WEKNORA_SANDBOX_E2B_SANDBOX_TTL:-}
+ - WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT=${WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT:-}
# Agent LLM call timeout
- WEKNORA_AGENT_LLM_TIMEOUT=${WEKNORA_AGENT_LLM_TIMEOUT:-}
- WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT=${WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT:-}
diff --git a/docs/agent-skills.md b/docs/agent-skills.md
index 4f7997088..2ba8baa1e 100644
--- a/docs/agent-skills.md
+++ b/docs/agent-skills.md
@@ -124,21 +124,74 @@ type AgentConfig struct {
### Sandbox 配置(环境变量)
-Sandbox 相关配置通过环境变量设置:
+下表的环境变量是**部署级默认值**。工作区还可以维护多份具名沙箱后端配置,智能体各自选用其一;未选择的智能体回落到这里的默认值(见「工作区沙箱后端配置」)。
| 环境变量 | 说明 | 默认值 |
|---------|------|--------|
-| `WEKNORA_SANDBOX_MODE` | sandbox 模式: `docker`, `local`, `disabled` | `disabled` |
+| `WEKNORA_SANDBOX_MODE` | sandbox 模式:`docker` / `local` / `cube` / `e2b` / `disabled` | `disabled` |
| `WEKNORA_SANDBOX_TIMEOUT` | 脚本执行超时(秒) | `60` |
-| `WEKNORA_SANDBOX_DOCKER_IMAGE` | 自定义 Docker 镜像 | `wechatopenai/weknora-sandbox:latest` |
+| `WEKNORA_SANDBOX_DOCKER_IMAGE` | 自定义 Docker 镜像(docker 模式) | `wechatopenai/weknora-sandbox:latest` |
+| `WEKNORA_SANDBOX_REDIS_NAMESPACE` | 会话→沙箱绑定的 Redis key 命名空间(cube / e2b 生效;未设置时复用 `WEKNORA_REDIS_NAMESPACE`) | `weknora` |
+| `WEKNORA_SANDBOX_CUBE_*` | Cube 后端专用配置,见 `.env.example` | — |
+| `WEKNORA_SANDBOX_E2B_*` | E2B 后端专用配置,见 `.env.example`(`WEKNORA_SANDBOX_E2B_API_KEY` 必填) | — |
### Sandbox 模式
-| 模式 | 说明 |
-|------|------|
-| `docker` | 使用 Docker 容器隔离(推荐) |
-| `local` | 本地进程执行(基础安全限制) |
-| `disabled` | 禁用脚本执行 |
+| 模式 | 状态 | 说明 |
+|------|------|------|
+| `docker` | 稳定 | 使用 Docker 容器隔离(推荐用于本地/单机部署) |
+| `local` | 基础 | 本地进程执行(仅基础白名单,无 MicroVM 隔离) |
+| `cube` | 稳定 | Tencent CubeSandbox MicroVM;会话级持久,支持多机(需 Redis) |
+| `e2b` | 稳定 | E2B 云端 MicroVM;会话级持久,支持多机(需 Redis);依赖第三方 SDK go-e2b |
+| `disabled` | — | 关闭本实例全部沙箱能力,含工作区具名配置 |
+
+### 工作区沙箱后端配置
+
+一个工作区可以维护**多份具名**沙箱后端配置(「设置 → 沙箱后端」),智能体在编辑弹窗的「能力扩展 → 沙箱后端」里各自选一份。不选就使用上表的部署级默认后端,行为与本特性上线前完全一致。
+
+同一后端类型可以有多份配置:例如两份 E2B 分别指向不同账号或区域,让不同智能体的技能脚本落在不同配额上。
+
+**具名配置是自包含的,不继承 `.env`。** 部署级 `WEKNORA_SANDBOX_*` 只服务「没有选择任何具名配置」的智能体;具名配置里留空的字段不会回退到那些值,必须自己填全:
+
+| 后端 | 必填 | 可留空 |
+|---|---|---|
+| Cube | API 端点、Proxy 端点、沙箱域名、模板 ID | API Key(自建部署通常无鉴权) |
+| E2B | API Key、模板 ID | API 端点、沙箱域名(go-e2b 自行解析默认值) |
+
+留空必填项在保存时就会被拒绝(HTTP 400,报文里列出缺哪些字段),而不是等到第一次执行技能才失败。HTTP 超时与沙箱 TTL 留空走**内置默认值**,同样不看 `.env`。唯一仍沿用部署值的是「执行超时」,因为它属于运维护栏而非后端身份。
+
+这条规则换来的是:库里那一行就是沙箱位置的完整描述。因此身份比较不必再去解析 `.env`,改 `.env` 也不会在无人察觉的情况下把某份配置重新指向别的账号。
+
+**会话与配置的绑定是「随沙箱同生共死」的钉子。** 会话首次创建沙箱时,把当时用的配置 ID 记在 `sessions.sandbox_config_id` 上;此后该会话的附件上传、产物收集、沙箱销毁都锁定在这份配置上。改智能体的选择**只影响之后新建的沙箱**——否则管理员改一次配置,正在进行的会话就会去错误的账号里找产物,销毁也会打空,留下一个没人知道 ID 的 paused 沙箱持续计费。
+
+**有沙箱在跑时改不了身份字段。** 身份字段分两组,成因不同但后果都足够严重:
+
+| 组 | 字段 | 一改会怎样 |
+|---|---|---|
+| 控制面 | 后端类型、API 端点、API Key | 旧沙箱**再也无法列举/删除/恢复**——新凭据没有权限动它们,而 `onTimeout=pause` 意味着 TTL 也不会回收|
+| 数据面 | E2B 沙箱域名;Cube 代理地址、沙箱域名 | 旧沙箱仍可删,但 envd 请求会打到错的主机 ⇒ 该配置下**所有活会话立刻失效**,而沙箱还活着继续计费 |
+
+因此这类修改会被拒绝(HTTP 409),界面会给出沙箱数量、受影响会话数,以及两条出路:**结束或删除那些会话**(删会话会销毁其沙箱),或者**新建一份配置**把智能体指过去(旧凭据原样留着,清理能力不丢)。**没有「释放沙箱」按钮**——那等于在管理员背后销毁正在进行的对话。
+
+**删除配置**只拦远端沙箱,不拦智能体引用:确认弹窗会列出仍指向它的智能体名单,但不阻止删除;删除后那些智能体执行技能时会明确报错,而不是静默换到别的后端。若后端已连不上、无法核实是否仍有沙箱,可以强制删除(这是唯一能强制的情形——能数出来的活沙箱永远不让强删)。
+
+**`sessions.sandbox_config_id` 取值语义:**
+
+| 值 | 含义 |
+|---|---|
+| `NULL` | 当前无活沙箱(删会话 / 销毁后会 Clear) |
+| `"-"` | 活沙箱建在**部署默认**(`.env` `WEKNORA_SANDBOX_*`)上 |
+| UUID | 活沙箱建在工作区某份**具名配置**上 |
+
+
+### 会话级 sandbox 部署要点
+
+- **binding store 自动选择**:无需专门的开关,进程根据 `REDIS_ADDR` 是否配置自动决定绑定存储——配置了 `REDIS_ADDR`(Redis 可用)时使用 Redis binding store,否则退回进程内内存 binding store。命名空间用 `WEKNORA_SANDBOX_REDIS_NAMESPACE`,未设置时依次回退到 `WEKNORA_REDIS_NAMESPACE`、`weknora`。
+- **多机部署(生产推荐)**:配置 `REDIS_ADDR`。多副本共享同一 session 的沙箱绑定,通过 Redis SET NX + 可续租分布式锁串行化 create / recover / delete。
+- **单机部署**:不配置 `REDIS_ADDR`(或 Lite 模式)时使用进程内内存 binding,仅限单实例。进程重启会丢失 session→sandbox 映射,remote 侧沙箱成为孤儿(注意:**TTL 到期只会暂停、不会销毁**,见下)。
+- **切换 provider**:不同 provider 的 sandbox ID 不通用。切换 `WEKNORA_SANDBOX_MODE` 后,旧 session 的 binding 会因 provider 不匹配被 CAS 替换成新 provider 的新沙箱;WeKnora 不做跨 provider 删除。
+- **⚠️ 孤儿沙箱不会被 TTL 自动回收**:会话沙箱创建时使用 `onTimeout=pause` + `autoResume=true`(见 `buildSessionCreateRequest`),因此 **TTL 到期是"暂停"而非"销毁"**——保留状态本就是 pause 的目的。加上 CAS 换绑会把旧 sandboxID 从 binding store 覆盖掉,被替换的沙箱会变成**无人知晓 ID 的 paused 孤儿**,持续占用快照存储与费用。删除会话(`session.go` 的 destroyer)与 lifecycle 的惰性 orphan cleanup 都覆盖不到这种情况。生产环境需依赖按 metadata 列举并与 binding 对账的清理任务来回收(`internal/sandbox/orphan_reaper.go`),且**必须显式包含 `paused` 状态**。对账维度是 `(tenant_id, config_id)` 而非仅 `tenant_id`:同一工作区的两份配置可能指向**同一个 provider 账号**(例如同一个 E2B Key 只差模板),只按 `tenant_id` 过滤会把另一份配置的沙箱一并误删。
+- **网络策略**:`cube` 与 `e2b` 默认开启公网出口和 public traffic,可在 create 时通过 provider-neutral `RemoteNetworkPolicy`(`AllowInternetAccess` / `AllowPublicTraffic` / `AllowOut` / `DenyOut`)精细化配置;两个 adapter 都实现了同一契约。
## Agent 工具
diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts
index 6c2e57e6c..71f67b2d2 100644
--- a/frontend/src/api/chat/index.ts
+++ b/frontend/src/api/chat/index.ts
@@ -1,4 +1,4 @@
-import { get, post, put, del, postChat } from "../../utils/request";
+import { get, post, put, del, postChat, getDown } from "../../utils/request";
@@ -80,3 +80,52 @@ export async function stopSession(session_id: string, message_id: string) {
export async function clearSessionMessages(session_id: string) {
return del(`/api/v1/sessions/${session_id}/messages`);
}
+
+// ---------------------------------------------------------------------------
+// Skill artifacts (files generated by skill scripts during agent turns)
+//
+// The backend keeps the storage URL private and indexes each file by its
+// position (:index) in the owning assistant message. The list endpoints
+// return metadata only — clients must go through downloadArtifact to fetch
+// the actual bytes so ownership checks always run server-side.
+// ---------------------------------------------------------------------------
+
+export interface ArtifactMeta {
+ index: number;
+ file_name: string;
+ file_type: string;
+ file_size: number;
+ source_path: string;
+ mod_time: string;
+ created_at: string;
+}
+
+// listMessageArtifacts returns the artifacts attached to a single assistant
+// message. Used by the drawer opened from the message action toolbar.
+export async function listMessageArtifacts(session_id: string, message_id: string) {
+ return get(
+ `/api/v1/sessions/${session_id}/messages/${message_id}/artifacts`,
+ );
+}
+
+// listSessionArtifacts returns every artifact recorded against the whole
+// session, in creation order. Powers "download everything generated in this
+// chat" drawers.
+export async function listSessionArtifacts(session_id: string) {
+ return get(`/api/v1/sessions/${session_id}/artifacts`);
+}
+
+// downloadArtifact streams a single artifact's bytes as a Blob so the caller
+// can trigger a browser download. A plain `<a href>` cannot be used because
+// axios attaches the Bearer token per request; issuing the download via
+// `getDown` keeps auth intact and lets the response be turned into an
+// object URL.
+export async function downloadArtifact(
+ session_id: string,
+ message_id: string,
+ index: number,
+): Promise<Blob> {
+ return getDown(
+ `/api/v1/sessions/${session_id}/messages/${message_id}/artifacts/${index}/download`,
+ );
+}
diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts
index ac09014b2..1370ebbb7 100644
--- a/frontend/src/api/system/index.ts
+++ b/frontend/src/api/system/index.ts
@@ -669,3 +669,239 @@ export async function purgeArchivedRuntimeTasks(
)
return response as unknown as { success: boolean; deleted: number }
}
+
+// --- Sandbox backend configuration (per workspace) ---
+
+export interface SandboxVolumeMountConfig {
+ enabled: boolean
+ mount_path?: string
+ provider?: string
+ volume_id?: string
+ volume_name?: string
+ volume_owner_fingerprint?: string
+}
+
+export interface SandboxCubeConfig {
+ api_url?: string
+ proxy_url?: string
+ sandbox_domain?: string
+ api_key?: string
+ template_id?: string
+ http_timeout_sec?: number
+ cube_sandbox_ttl_seconds?: number
+}
+
+export interface SandboxE2BConfig {
+ api_url?: string
+ sandbox_domain?: string
+ api_key?: string
+ template_id?: string
+ http_timeout_sec?: number
+ e2b_sandbox_ttl_seconds?: number
+}
+
+export interface SandboxConfig {
+ sandbox_type?: string
+ default_timeout_sec?: number
+ env_vars?: Record<string, string>
+ volume_mount?: SandboxVolumeMountConfig
+ cube?: SandboxCubeConfig
+ e2b?: SandboxE2BConfig
+ docker?: { image?: string }
+}
+
+/** `ok: null` means the probe was not executed in this run. */
+export interface SandboxCheckItem {
+ name: string
+ ok: boolean | null
+ message?: string
+ latency_ms?: number
+}
+
+export interface SandboxCheckResult {
+ ok: boolean
+ provider: string
+ checks: SandboxCheckItem[]
+ capabilities?: Record<string, boolean>
+}
+
+/** Non-secret, inheritable defaults from the deployment's .env configuration. */
+export interface SandboxProviderDefaults {
+ api_url?: string
+ proxy_url?: string
+ sandbox_domain?: string
+ template_id?: string
+ api_key_configured: boolean
+ http_timeout_sec?: number
+ sandbox_ttl_seconds?: number
+}
+
+export interface SandboxConfigDefaults {
+ sandbox_type: string
+ default_timeout_sec?: number
+ docker_image?: string
+ cube?: SandboxProviderDefaults
+ e2b?: SandboxProviderDefaults
+}
+
+/** One named sandbox backend config. Credentials arrive masked. */
+export interface SandboxConfigRecord {
+ id: string
+ name: string
+ description?: string
+ sandbox_type: string
+ config: SandboxConfig
+ created_at: string
+ updated_at: string
+}
+
+/** Create/update payload. */
+export interface SandboxConfigUpsert {
+ name: string
+ description?: string
+ config: SandboxConfig
+}
+
+/**
+ * What a config currently holds. `sandbox_count` comes from the provider, so a
+ * non-zero value is authoritative: identity edits and deletion are refused
+ * until it reaches zero.
+ *
+ * `unverifiable` means the provider could not be reached, so the count is
+ * UNKNOWN rather than zero — never render it as "0 sandboxes".
+ */
+export interface SandboxInventory {
+ sandbox_count: number
+ session_ids?: string[]
+ agent_names?: string[]
+ unverifiable?: boolean
+}
+
+/** Named sandbox backends that support per-config credentials (cube/e2b only). */
+export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b'] as const
+
+export function isNamedSandboxBackend(type: string): boolean {
+ return (NAMED_SANDBOX_BACKEND_TYPES as readonly string[]).includes(type)
+}
+
+/**
+ * Returns every config of the workspace plus the deployment defaults an empty
+ * field inherits. An empty list means "no named config yet", in which case
+ * agents run on those defaults — which is NOT the same as disabled.
+ */
+export function listSandboxConfigs(): Promise<{
+ data: SandboxConfigRecord[]
+ defaults?: SandboxConfigDefaults
+ workspace_scripts_disabled?: boolean
+}> {
+ return get('/api/v1/sandbox-configs') as unknown as Promise<{
+ data: SandboxConfigRecord[]
+ defaults?: SandboxConfigDefaults
+ workspace_scripts_disabled?: boolean
+ }>
+}
+
+export function setSandboxWorkspacePolicy(scriptsDisabled: boolean): Promise<{
+ workspace_scripts_disabled: boolean
+}> {
+ return put('/api/v1/sandbox-configs/workspace-policy', {
+ scripts_disabled: scriptsDisabled,
+ }) as unknown as Promise<{ workspace_scripts_disabled: boolean }>
+}
+
+export function createSandboxConfig(
+ payload: SandboxConfigUpsert,
+): Promise<{ data: SandboxConfigRecord }> {
+ return post('/api/v1/sandbox-configs', payload) as unknown as Promise<{
+ data: SandboxConfigRecord
+ }>
+}
+
+export function getSandboxConfigById(id: string): Promise<{ data: SandboxConfigRecord }> {
+ return get(`/api/v1/sandbox-configs/${id}`) as unknown as Promise<{
+ data: SandboxConfigRecord
+ }>
+}
+
+export function updateSandboxConfigById(
+ id: string,
+ payload: SandboxConfigUpsert,
+): Promise<{ data: SandboxConfigRecord }> {
+ return put(`/api/v1/sandbox-configs/${id}`, payload) as unknown as Promise<{
+ data: SandboxConfigRecord
+ }>
+}
+
+/**
+ * `force` only overrides an inventory the backend could not verify; it never
+ * overrides sandboxes the backend can actually see. Ask for it exclusively in
+ * response to a `sandbox_inventory_unverifiable` conflict.
+ */
+export function deleteSandboxConfig(id: string, force = false): Promise<void> {
+ const query = force ? '?force=true' : ''
+ return del(`/api/v1/sandbox-configs/${id}${query}`) as unknown as Promise<void>
+}
+
+export function getSandboxConfigInventory(id: string): Promise<{ data: SandboxInventory }> {
+ return get(`/api/v1/sandbox-configs/${id}/sandboxes`) as unknown as Promise<{
+ data: SandboxInventory
+ }>
+}
+
+/**
+ * Probe a sandbox configuration without saving it. Redacted secrets are
+ * resolved server-side, so pass `config_id` alongside an edited `config` to
+ * test unsaved changes without retyping an API key. Omit `config` to probe a
+ * stored config as-is.
+ *
+ * `deep` additionally creates and destroys one sandbox, which is the only way
+ * to validate the template ID, Cube's proxy data plane and outbound egress.
+ * It consumes real sandbox time.
+ */
+export function checkSandboxConfig(payload: {
+ config?: SandboxConfig
+ config_id?: string
+ deep?: boolean
+}): Promise<{ data: SandboxCheckResult }> {
+ return post('/api/v1/system/sandbox-check', payload) as unknown as Promise<{
+ data: SandboxCheckResult
+ }>
+}
+
+/**
+ * The two refusals a save or a delete can hit. They mean opposite things:
+ * `sandboxes_still_live` says the backend counted live sandboxes, so the only
+ * ways forward are ending the owning sessions or creating a second config;
+ * `sandbox_inventory_unverifiable` says the backend is unreachable, so nothing
+ * could be counted — the one case a force delete may override.
+ */
+export type SandboxConflictCode = 'sandboxes_still_live' | 'sandbox_inventory_unverifiable'
+
+export interface SandboxConflict {
+ code: SandboxConflictCode
+ message?: string
+ /** Present for `sandboxes_still_live`; there is nothing to report otherwise. */
+ inventory?: SandboxInventory
+}
+
+/**
+ * Reads a sandbox-config conflict out of a rejected request, or returns null
+ * when the failure is anything else.
+ *
+ * The interceptor spreads the response body onto the rejection, so the code
+ * sits at `err.error.code`. Parsing it in one place keeps callers from
+ * hard-coding that shape — and from confusing the two conflicts, which drive
+ * different recovery paths in the UI.
+ */
+export function parseSandboxConflict(err: unknown): SandboxConflict | null {
+ if (typeof err !== 'object' || err === null) return null
+ const detail = (err as { error?: { code?: string; message?: string; data?: SandboxInventory } }).error
+ if (!detail || typeof detail !== 'object') return null
+ if (
+ detail.code !== 'sandboxes_still_live' &&
+ detail.code !== 'sandbox_inventory_unverifiable'
+ ) {
+ return null
+ }
+ return { code: detail.code, message: detail.message, inventory: detail.data }
+}
diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue
new file mode 100644
index 000000000..9e5bfaf86
--- /dev/null
+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue
@@ -0,0 +1,506 @@
+<template>
+ <t-drawer
+ :visible="visible"
+ :header="record ? $t('settings.sandbox.editTitle') : $t('settings.sandbox.createTitle')"
+ size="620px"
+ :confirm-btn="{ content: $t('common.save'), loading: saving }"
+ :cancel-btn="{ content: $t('common.cancel') }"
+ @confirm="save"
+ @close="close"
+ @update:visible="(v: boolean) => emit('update:visible', v)"
+ >
+ <!--
+ Identity-change refusals must sit at the top: the form is long and the
+ admin otherwise saves, sees nothing, and assumes the click did nothing.
+ -->
+ <div v-if="conflict" ref="conflictAlertRef" class="blocked blocked-top">
+ <t-alert v-if="conflict.code === 'sandboxes_still_live'" theme="warning"
+ :message="$t('settings.sandbox.sandboxesStillLive', { count: conflict.inventory?.sandbox_count ?? 0 })">
+ <template #description>
+ <p v-if="affectedSessionCount">{{ $t('settings.sandbox.affectedSessions', { count: affectedSessionCount }) }}</p>
+ <p v-if="conflict.inventory?.agent_names?.length">
+ {{ $t('settings.sandbox.affectedAgents', { names: conflict.inventory.agent_names.join('、') }) }}
+ </p>
+ <p>{{ $t('settings.sandbox.blockedHint') }}</p>
+ </template>
+ </t-alert>
+ <t-alert v-else theme="warning" :message="$t('settings.sandbox.unverifiableBlocked')">
+ <template #description>
+ <p>{{ $t('settings.sandbox.unverifiableSaveHint') }}</p>
+ </template>
+ </t-alert>
+ </div>
+
+ <t-form label-align="top">
+ <t-form-item :label="$t('settings.sandbox.configName')" :status="nameError ? 'error' : undefined"
+ :tips="nameError || undefined">
+ <t-input v-model="name" :placeholder="$t('settings.sandbox.configNamePlaceholder')" />
+ </t-form-item>
+ <t-form-item :label="$t('settings.sandbox.configDescription')">
+ <t-input v-model="description" :placeholder="$t('settings.sandbox.configDescriptionPlaceholder')" />
+ </t-form-item>
+
+ <!--
+ Only while editing: a config being created owns no sandboxes yet, so
+ warning that these fields are locked would describe a restriction that
+ does not apply.
+ -->
+ <t-alert v-if="record" theme="info" class="identity-hint"
+ :message="$t('settings.sandbox.identityFieldHint')" />
+
+ <t-form-item :label="$t('settings.sandbox.backend')">
+ <t-select v-model="backend" @change="onBackendChange">
+ <t-option v-for="opt in backendOptions" :key="opt" :value="opt" :label="backendLabel(opt)" />
+ </t-select>
+ </t-form-item>
+
+ <!--
+ Placeholders are format examples, never the deployment's own values: a
+ named config inherits nothing, so showing what .env holds would suggest
+ an empty field still works.
+ -->
+ <!-- Cube -->
+ <template v-if="backend === 'cube'">
+ <t-form-item :label="requiredLabel('apiUrl')" :status="fieldStatus('api_url')" :tips="fieldTip('api_url')">
+ <t-input v-model="cube.api_url" placeholder="http://cube.example.com:33000"
+ @input="onFieldInput('api_url')" />
+ </t-form-item>
+ <t-form-item :label="requiredLabel('proxyUrl')" :status="fieldStatus('proxy_url')"
+ :tips="fieldTip('proxy_url')">
+ <t-input v-model="cube.proxy_url" placeholder="http://cube.example.com:80"
+ @input="onFieldInput('proxy_url')" />
+ </t-form-item>
+ <t-form-item :label="requiredLabel('sandboxDomain')" :status="fieldStatus('sandbox_domain')"
+ :tips="fieldTip('sandbox_domain')">
+ <t-input v-model="cube.sandbox_domain" placeholder="cube.app" @input="onFieldInput('sandbox_domain')" />
+ </t-form-item>
+ <t-form-item :label="$t('settings.sandbox.apiKey')" :help="$t('settings.sandbox.cubeApiKeyOptional')">
+ <t-input v-model="cube.api_key" type="password" :placeholder="secretPlaceholder" />
+ </t-form-item>
+ <t-form-item :label="requiredLabel('templateId')" :status="fieldStatus('template_id')"
+ :tips="fieldTip('template_id')">
+ <t-input v-model="cube.template_id" placeholder="tpl-xxxxxxxx" @input="onFieldInput('template_id')" />
+ </t-form-item>
+ <div class="timeout-row">
+ <t-form-item :label="$t('settings.sandbox.httpTimeout')">
+ <t-input-number v-model="cube.http_timeout_sec" :min="0" theme="column" placeholder="30" />
+ </t-form-item>
+ <t-form-item :label="$t('settings.sandbox.sandboxTtl')">
+ <t-input-number v-model="cube.cube_sandbox_ttl_seconds" :min="0" theme="column" placeholder="1800" />
+ </t-form-item>
+ <t-form-item :label="$t('settings.sandbox.defaultTimeout')">
+ <t-input-number v-model="defaultTimeoutSec" :min="0" theme="column"
+ :placeholder="String(defaults?.default_timeout_sec || 60)" />
+ </t-form-item>
+ </div>
+ </template>
+
+ <!-- E2B -->
+ <template v-else-if="backend === 'e2b'">
+ <t-form-item :label="$t('settings.sandbox.apiUrl')" :help="$t('settings.sandbox.e2bApiUrlOptional')">
+ <t-input v-model="e2b.api_url" placeholder="https://api.e2b.app" @input="invalidateCheck" />
+ </t-form-item>
+ <t-form-item :label="$t('settings.sandbox.sandboxDomain')" :help="$t('settings.sandbox.e2bDomainOptional')">
+ <t-input v-model="e2b.sandbox_domain" placeholder="e2b.app" />
+ </t-form-item>
+ <t-form-item :label="requiredLabel('apiKey')" :status="fieldStatus('api_key')" :tips="fieldTip('api_key')">
+ <t-input v-model="e2b.api_key" type="password" :placeholder="secretPlaceholder"
+ @input="onFieldInput('api_key')" />
+ </t-form-item>
+ <t-form-item :label="requiredLabel('templateId')" :status="fieldStatus('template_id')"
+ :tips="fieldTip('template_id')">
+ <t-input v-model="e2b.template_id" placeholder="xxxxxxxxxxxxxxxx"
+ @input="onFieldInput('template_id')" />
+ </t-form-item>
+ <div class="timeout-row">
+ <t-form-item :label="$t('settings.sandbox.httpTimeout')">
+ <t-input-number v-model="e2b.http_timeout_sec" :min="0" theme="column" placeholder="30" />
+ </t-form-item>
+ <t-form-item :label="$t('settings.sandbox.sandboxTtl')">
+ <t-input-number v-model="e2b.e2b_sandbox_ttl_seconds" :min="0" theme="column" placeholder="300" />
+ </t-form-item>
+ <t-form-item :label="$t('settings.sandbox.defaultTimeout')">
+ <t-input-number v-model="defaultTimeoutSec" :min="0" theme="column"
+ :placeholder="String(defaults?.default_timeout_sec || 60)" />
+ </t-form-item>
+ </div>
+ </template>
+
+ <!-- Environment variables: a map on the wire, editable rows in the UI. -->
+ <t-form-item :label="$t('settings.sandbox.envVars')"
+ :help="$t('settings.sandbox.envVarsHint')">
+ <div class="env-rows">
+ <div v-for="(row, index) in envRows" :key="index" class="env-row">
+ <t-input v-model="row.key" :placeholder="$t('settings.sandbox.envKey')" style="width: 200px" />
+ <t-input v-model="row.value" type="password" :placeholder="$t('settings.sandbox.envValue')"
+ style="width: 220px" />
+ <t-button variant="text" theme="danger" @click="envRows.splice(index, 1)">
+ {{ $t('settings.sandbox.removeRow') }}
+ </t-button>
+ </div>
+ <t-button variant="outline" size="small" @click="envRows.push({ key: '', value: '' })">
+ {{ $t('settings.sandbox.addRow') }}
+ </t-button>
+ </div>
+ </t-form-item>
+ </t-form>
+
+ <div v-if="isRemoteBackend" class="check-actions">
+ <t-button variant="outline" :loading="checking" @click="runCheck(false)">
+ {{ $t('settings.sandbox.testConnection') }}
+ </t-button>
+ <t-popconfirm :content="$t('settings.sandbox.deepCheckConfirm')" @confirm="runCheck(true)">
+ <t-button variant="outline" :loading="checking">
+ {{ $t('settings.sandbox.deepCheck') }}
+ </t-button>
+ </t-popconfirm>
+ </div>
+
+ <div v-if="checkResult" ref="checkResultRef" class="check-result">
+ <t-alert :theme="checkResult.ok ? 'success' : 'error'"
+ :message="checkResult.ok ? $t('settings.sandbox.checkPassed') : $t('settings.sandbox.checkFailed')" />
+ <ul class="check-list">
+ <li v-for="item in checkResult.checks" :key="item.name" class="check-item">
+ <t-icon :name="item.ok === true ? 'check-circle-filled'
+ : item.ok === false ? 'close-circle-filled' : 'minus-circle'"
+ :class="item.ok === true ? 'ok' : item.ok === false ? 'err' : 'skip'" />
+ <span class="check-name">{{ checkLabel(item.name) }}</span>
+ <span v-if="item.latency_ms" class="check-latency">{{ item.latency_ms }} ms</span>
+ <span v-if="item.message" class="check-message">{{ item.message }}</span>
+ </li>
+ </ul>
+ <t-alert v-if="checkResult.capabilities && checkResult.capabilities.supports_volumes === false" theme="warning"
+ :message="$t('settings.sandbox.noVolumeSupport')" />
+ </div>
+
+ </t-drawer>
+</template>
+
+<script setup lang="ts">
+import { computed, nextTick, reactive, ref, watch } from 'vue'
+import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
+import {
+ checkSandboxConfig,
+ createSandboxConfig,
+ parseSandboxConflict,
+ updateSandboxConfigById,
+ type SandboxCheckResult,
+ type SandboxConfig,
+ type SandboxConfigDefaults,
+ type SandboxConfigRecord,
+ type SandboxConflict,
+ type SandboxCubeConfig,
+ type SandboxE2BConfig,
+ isNamedSandboxBackend,
+ NAMED_SANDBOX_BACKEND_TYPES,
+} from '@/api/system'
+
+const props = defineProps<{
+ visible: boolean
+ record: SandboxConfigRecord | null
+ presetType?: string
+ defaults: SandboxConfigDefaults | null
+}>()
+
+const emit = defineEmits<{
+ (e: 'update:visible', value: boolean): void
+ (e: 'saved'): void
+}>()
+
+const { t } = useI18n()
+
+// The backend echoes secrets as this placeholder; submitting it unchanged keeps
+// the stored value, so the form never needs the real key.
+const secretPlaceholder = '***'
+
+const backendOptions = [...NAMED_SANDBOX_BACKEND_TYPES]
+
+const saving = ref(false)
+const checking = ref(false)
+const checkResult = ref<SandboxCheckResult | null>(null)
+const conflict = ref<SandboxConflict | null>(null)
+const conflictAlertRef = ref<HTMLElement | null>(null)
+const checkResultRef = ref<HTMLElement | null>(null)
+const nameError = ref('')
+
+const name = ref('')
+const description = ref('')
+const backend = ref('')
+// undefined rather than 0 so the input renders empty and shows its placeholder,
+// matching the HTTP timeout / TTL fields. A literal 0 would read as a real value.
+const defaultTimeoutSec = ref<number | undefined>(undefined)
+const cube = reactive<SandboxCubeConfig>({})
+const e2b = reactive<SandboxE2BConfig>({})
+const envRows = ref<{ key: string; value: string }[]>([])
+
+// Only remote backends have a control plane worth probing.
+const isRemoteBackend = computed(() => backend.value === 'cube' || backend.value === 'e2b')
+
+const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)
+const checkLabel = (probe: string) => t(`settings.sandbox.checks.${probe}`, probe)
+
+// Mirrors sandbox.MissingRequiredFields on the server. Duplicated on purpose:
+// the server stays the authority, this only spares the admin a round-trip and
+// points at the offending input instead of showing one combined message.
+const REQUIRED_FIELDS: Record<string, string[]> = {
+ cube: ['api_url', 'proxy_url', 'sandbox_domain', 'template_id'],
+ e2b: ['api_key', 'template_id'],
+}
+
+const fieldErrors = ref<Record<string, string>>({})
+
+const fieldStatus = (field: string) => (fieldErrors.value[field] ? 'error' : undefined)
+const fieldTip = (field: string) => fieldErrors.value[field] || undefined
+
+const requiredLabel = (labelKey: string) => `${t(`settings.sandbox.${labelKey}`)} *`
+
+// Clearing on input rather than re-validating keeps the error from flickering
+// back while the admin is still halfway through typing a URL.
+function onFieldInput(field: string) {
+ delete fieldErrors.value[field]
+ invalidateCheck()
+}
+
+function validateRequiredFields(): boolean {
+ const required = REQUIRED_FIELDS[backend.value] || []
+ const values = (backend.value === 'cube' ? cube : e2b) as Record<string, unknown>
+ const errors: Record<string, string> = {}
+ for (const field of required) {
+ const value = values[field]
+ if (typeof value !== 'string' || value.trim() === '') {
+ errors[field] = t('settings.sandbox.fieldRequired')
+ }
+ }
+ fieldErrors.value = errors
+ return Object.keys(errors).length === 0
+}
+
+const affectedSessionCount = computed(() => conflict.value?.inventory?.session_ids?.length || 0)
+
+function defaultBackendType(): string {
+ const fromRecord = props.record?.config?.sandbox_type || props.presetType || ''
+ if (isNamedSandboxBackend(fromRecord)) return fromRecord
+ const fromDeploy = props.defaults?.sandbox_type || ''
+ if (isNamedSandboxBackend(fromDeploy)) return fromDeploy
+ return 'cube'
+}
+
+function reset() {
+ const cfg: SandboxConfig = props.record?.config || {}
+ name.value = props.record?.name || ''
+ description.value = props.record?.description || ''
+ backend.value = isNamedSandboxBackend(cfg.sandbox_type || '')
+ ? cfg.sandbox_type!
+ : defaultBackendType()
+ defaultTimeoutSec.value = cfg.default_timeout_sec || undefined
+ // Replace rather than merge: a reused reactive object would otherwise carry
+ // the previously edited config's fields into the next one opened.
+ Object.keys(cube).forEach((key) => delete (cube as Record<string, unknown>)[key])
+ Object.keys(e2b).forEach((key) => delete (e2b as Record<string, unknown>)[key])
+ Object.assign(cube, cfg.cube || {})
+ Object.assign(e2b, cfg.e2b || {})
+ envRows.value = Object.entries(cfg.env_vars || {}).map(([key, value]) => ({ key, value }))
+ checkResult.value = null
+ conflict.value = null
+ nameError.value = ''
+ fieldErrors.value = {}
+}
+
+watch(() => props.visible, (open) => {
+ if (open) reset()
+})
+
+function collectPayload(): SandboxConfig {
+ const envVars: Record<string, string> = {}
+ for (const row of envRows.value) {
+ const key = row.key.trim()
+ if (key) envVars[key] = row.value
+ }
+ const payload: SandboxConfig = {
+ sandbox_type: backend.value,
+ default_timeout_sec: defaultTimeoutSec.value || undefined,
+ env_vars: envVars,
+ }
+ // Send only the selected backend's block so an unused one cannot fail
+ // validation (e.g. a stale private URL left in the other tab).
+ if (backend.value === 'cube') payload.cube = { ...cube }
+ if (backend.value === 'e2b') payload.e2b = { ...e2b }
+ return payload
+}
+
+function close() {
+ emit('update:visible', false)
+}
+
+async function save() {
+ const trimmed = name.value.trim()
+ if (!trimmed) {
+ nameError.value = t('settings.sandbox.configNameRequired')
+ return
+ }
+ nameError.value = ''
+ if (!validateRequiredFields()) return
+ saving.value = true
+ conflict.value = null
+ try {
+ const payload = { name: trimmed, description: description.value, config: collectPayload() }
+ if (props.record) {
+ await updateSandboxConfigById(props.record.id, payload)
+ } else {
+ await createSandboxConfig(payload)
+ }
+ MessagePlugin.success(t('common.saveSuccess'))
+ emit('saved')
+ close()
+ } catch (e: any) {
+ const refusal = parseSandboxConflict(e)
+ if (refusal) {
+ // Keep the drawer open with the form intact: the admin has to act
+ // elsewhere first, and retyping everything afterwards would be cruel.
+ conflict.value = refusal
+ await nextTick()
+ conflictAlertRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
+ return
+ }
+ MessagePlugin.error(e?.message || t('settings.sandbox.saveFailed'))
+ } finally {
+ saving.value = false
+ }
+}
+
+async function runCheck(deep: boolean) {
+ // The probe builds a real client, so an incomplete config would come back as
+ // a generic client_build failure instead of naming the empty field.
+ if (!validateRequiredFields()) return
+ checking.value = true
+ checkResult.value = null
+ try {
+ // config_id lets the backend resolve masked secrets against the stored row,
+ // so an edited form can be probed without retyping the API key.
+ const res = await checkSandboxConfig({
+ config: collectPayload(),
+ config_id: props.record?.id,
+ deep,
+ })
+ checkResult.value = res?.data || null
+ if (checkResult.value) {
+ await nextTick()
+ checkResultRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
+ }
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('settings.sandbox.checkFailed'))
+ } finally {
+ checking.value = false
+ }
+}
+
+// A result that no longer matches the form is worse than none.
+function invalidateCheck() {
+ checkResult.value = null
+}
+
+// The two backends require different fields, so carrying errors across a switch
+// would flag inputs the admin can no longer even see.
+function onBackendChange() {
+ fieldErrors.value = {}
+ invalidateCheck()
+}
+</script>
+
+<style scoped>
+.identity-hint {
+ margin-bottom: 16px;
+}
+
+.timeout-row {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 12px;
+ margin-bottom: 24px;
+}
+
+.timeout-row :deep(.t-form__item) {
+ margin-bottom: 0;
+}
+
+.timeout-row :deep(.t-input-number) {
+ width: 100%;
+}
+
+.env-rows {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ align-items: flex-start;
+}
+
+.env-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.check-actions {
+ display: flex;
+ gap: 12px;
+ margin-top: 4px;
+}
+
+.check-result {
+ margin-top: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.check-list {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.check-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+}
+
+.check-item .ok {
+ color: var(--td-success-color);
+}
+
+.check-item .err {
+ color: var(--td-error-color);
+}
+
+.check-item .skip {
+ color: var(--td-text-color-placeholder);
+}
+
+.check-name {
+ min-width: 140px;
+}
+
+.check-latency,
+.check-message {
+ color: var(--td-text-color-secondary);
+}
+
+.blocked {
+ margin-top: 16px;
+}
+
+.blocked-top {
+ margin-top: 0;
+ margin-bottom: 16px;
+}
+
+.blocked p {
+ margin: 4px 0 0;
+}
+</style>
diff --git a/frontend/src/composables/useChatStreamHandler.ts b/frontend/src/composables/useChatStreamHandler.ts
index 407f23917..0f862a50e 100644
--- a/frontend/src/composables/useChatStreamHandler.ts
+++ b/frontend/src/composables/useChatStreamHandler.ts
@@ -813,6 +813,16 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
onTurnComplete?.(message)
fullContent.value = ''
currentAssistantMessageId.value = ''
+ // Hydrate skill-generated artifacts as soon as the SSE completion
+ // event arrives — without this the download button only appears
+ // after a page refresh (the assistant message row is fetched via
+ // getMessageList which does include the artifacts JSON column).
+ // botmsg.vue / AgentStreamDisplay.vue read `message.artifacts`
+ // reactively to decide whether to render the download button.
+ const streamedArtifacts = (dataPayload as any)?.artifacts
+ if (Array.isArray(streamedArtifacts) && streamedArtifacts.length) {
+ message.artifacts = streamedArtifacts
+ }
if (message.agentEventStream) {
;(message.agentEventStream as ChatMessage[]).push({
type: 'agent_complete',
diff --git a/frontend/src/config/settingsAccess.ts b/frontend/src/config/settingsAccess.ts
index c5b9507f6..d13398b2f 100644
--- a/frontend/src/config/settingsAccess.ts
+++ b/frontend/src/config/settingsAccess.ts
@@ -17,6 +17,7 @@ export const SETTINGS_SECTION_MIN_ROLE: Record<string, SettingsRoleKey> = {
vectorstore: 'admin',
parser: 'admin',
storage: 'admin',
+ sandbox: 'admin',
mcp: 'admin',
system: 'viewer',
userprofile: 'viewer',
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 882717773..8307949fb 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -801,6 +801,13 @@ export default {
think: 'Thinking',
copy: 'Copy',
addToKnowledgeBase: 'Add to Knowledge Base',
+ artifactDrawer: {
+ buttonTitle: 'Download files generated in this reply',
+ title: 'Generated files',
+ empty: 'No downloadable files were generated this turn.',
+ download: 'Download',
+ downloadFailed: 'Download failed, please retry.',
+ },
updatePlan: 'Update Plan',
webSearchFound: 'Found <strong>{count}</strong> web search result(s)',
toolFallback: 'Tool',
@@ -1007,6 +1014,15 @@ export default {
selectSkills: 'Select Skills',
selectSkillsDesc: 'Choose which Skills to enable',
noSkillsAvailable: 'No preloaded Skills available',
+ sandboxConfig: 'Sandbox backend',
+ sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
+ sandboxBackend: 'Sandbox backend',
+ sandboxBackendDefault: 'Use deployment defaults',
+ sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',
+ sandboxBackendMissing: 'Config deleted',
+ sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',
+ sandboxInfoTitle: 'Why choose a backend?',
+ sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',
skillsInfoTitle: 'What are Skills?',
skillsInfoContent: 'Skills are preloaded professional knowledge modules that provide domain-specific instructions, workflows, and tool support for the Agent. When enabled, the Agent will automatically load relevant knowledge when needed.'
},
@@ -1037,6 +1053,101 @@ export default {
vectorStoreEngine: 'Vector DB Engine',
parserEngine: 'Parser Engine',
storageEngine: 'Storage Engine',
+ sandbox: {
+ title: 'Sandbox Backend',
+ description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',
+ loading: 'Loading sandbox configuration...',
+ loadFailed: 'Failed to load sandbox configuration',
+ backend: 'Sandbox backend',
+ backendHint: 'Leave unset to inherit the global default',
+ addConfig: 'Add sandbox backend',
+ viewDeployDefaults: 'View deployment defaults',
+ deployDefaultsTitle: 'Deployment defaults',
+ deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',
+ deployDefaultBackend: 'Default backend',
+ apiKeyConfigured: 'Configured',
+ apiKeyNotConfigured: 'Not configured',
+ configName: 'Config name',
+ configNamePlaceholder: 'e.g. Production E2B',
+ configNameRequired: 'Please enter a config name',
+ configDescription: 'Description',
+ configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',
+ createTitle: 'Add sandbox backend',
+ editTitle: 'Edit sandbox backend',
+ noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',
+ identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
+ viewSandboxes: 'View sandbox usage',
+ inventoryTitle: 'Sandbox usage',
+ inventoryFailed: 'Failed to load sandbox usage',
+ sandboxCount: 'Sandboxes',
+ sandboxCountUnknown: 'Unknown (backend unreachable)',
+ inventoryUnverifiableHint: 'The backend is unreachable, so the sandbox count is unknown — that is not the same as none.',
+ sandboxesStillLive: 'This config still owns {count} running or paused sandbox(es), so identity fields cannot be changed yet.',
+ blockedHint: 'End or delete those sessions (deleting a session destroys its sandbox), or create a second config and point the agents at it.',
+ unverifiableBlocked: 'The backend cannot be reached to verify whether sandboxes remain, so the stored credentials will not be overwritten.',
+ unverifiableSaveHint: 'Restore connectivity first; if the backend is gone for good, create a second config and point the agents at it.',
+ affectedSessions: '{count} session(s) affected.',
+ affectedAgents: 'Agents using this config: {names}',
+ confirmDelete: 'Delete sandbox backend "{name}"?',
+ confirmDeleteWithAgents: 'Delete sandbox backend "{name}"? {agents}They will fail on their next skill execution.',
+ deleteFailed: 'Failed to delete',
+ deleted: 'Deleted',
+ forceDeleteTitle: 'Sandbox usage cannot be verified',
+ forceDeleteConfirm: 'The backend cannot be reached to verify whether sandboxes remain. If it is gone for good you can force-delete this config; if it is only temporarily unreachable, forcing it leaves any remaining sandboxes with nobody to reclaim them. Force delete anyway?',
+ forceDelete: 'Force delete',
+ disableScripts: 'Disable sandbox execution',
+ enableScripts: 'Enable sandbox execution',
+ disableScriptsConfirm:
+ 'All agents in this workspace — will no longer run skill scripts in a sandbox. They can still read skill content. Existing remote sandboxes are not destroyed automatically; end or delete the related sessions to release them. Continue?',
+ scriptsDisabled: 'Sandbox execution disabled for this workspace',
+ scriptsEnabled: 'Sandbox execution restored for this workspace',
+ policySaveFailed: 'Failed to update sandbox execution policy',
+ legacyConfig: 'Deprecated',
+ namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',
+ fieldRequired: 'Required',
+ cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
+ e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
+ e2bDomainOptional: 'Optional — the SDK default is used when empty',
+ backends: {
+ disabled: 'Disabled',
+ local: 'Local process',
+ docker: 'Docker',
+ cube: 'CubeSandbox',
+ e2b: 'E2B',
+ },
+ apiUrl: 'API endpoint',
+ proxyUrl: 'Proxy endpoint',
+ sandboxDomain: 'Sandbox domain',
+ apiKey: 'API key',
+ templateId: 'Template ID',
+ httpTimeout: 'HTTP timeout (s)',
+ sandboxTtl: 'Sandbox TTL (s)',
+ dockerImage: 'Docker image',
+ defaultTimeout: 'Execution timeout (s)',
+ envVars: 'Environment variables',
+ envKey: 'Name',
+ envValue: 'Value',
+ envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
+ addRow: 'Add variable',
+ removeRow: 'Remove',
+ save: 'Save',
+ saved: 'Saved. Applies to new sessions.',
+ saveFailed: 'Failed to save',
+ testConnection: 'Test connection',
+ deepCheck: 'Full verification',
+ deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',
+ checkPassed: 'All checks passed',
+ checkFailed: 'Some checks failed',
+ noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
+ checks: {
+ client_build: 'Client construction',
+ api_url_reachable: 'Endpoint reachability',
+ credential_valid: 'Credential validity',
+ template_exists: 'Template existence',
+ sandbox_exec: 'In-sandbox execution',
+ egress_available: 'Outbound network',
+ },
+ },
mcpService: 'MCP Service',
versionInfo: 'Version Info',
taskQueue: 'Task Queues',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index d7eaf24c5..8d87c2c2e 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -4652,6 +4652,101 @@ export default {
vectorStoreEngine: '벡터 DB 엔진',
parserEngine: '파싱 엔진',
storageEngine: '스토리지 엔진',
+ sandbox: {
+ title: 'Sandbox Backend',
+ description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',
+ loading: 'Loading sandbox configuration...',
+ loadFailed: 'Failed to load sandbox configuration',
+ backend: 'Sandbox backend',
+ backendHint: 'Leave unset to inherit the global default',
+ addConfig: 'Add sandbox backend',
+ viewDeployDefaults: 'View deployment defaults',
+ deployDefaultsTitle: 'Deployment defaults',
+ deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',
+ deployDefaultBackend: 'Default backend',
+ apiKeyConfigured: 'Configured',
+ apiKeyNotConfigured: 'Not configured',
+ configName: 'Config name',
+ configNamePlaceholder: 'e.g. Production E2B',
+ configNameRequired: 'Please enter a config name',
+ configDescription: 'Description',
+ configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',
+ createTitle: 'Add sandbox backend',
+ editTitle: 'Edit sandbox backend',
+ noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',
+ identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
+ viewSandboxes: 'View sandbox usage',
+ inventoryTitle: 'Sandbox usage',
+ inventoryFailed: 'Failed to load sandbox usage',
+ sandboxCount: 'Sandboxes',
+ sandboxCountUnknown: 'Unknown (backend unreachable)',
+ inventoryUnverifiableHint: 'The backend is unreachable, so the sandbox count is unknown — that is not the same as none.',
+ sandboxesStillLive: 'This config still owns {count} running or paused sandbox(es), so identity fields cannot be changed yet.',
+ blockedHint: 'End or delete those sessions (deleting a session destroys its sandbox), or create a second config and point the agents at it.',
+ unverifiableBlocked: 'The backend cannot be reached to verify whether sandboxes remain, so the stored credentials will not be overwritten.',
+ unverifiableSaveHint: 'Restore connectivity first; if the backend is gone for good, create a second config and point the agents at it.',
+ affectedSessions: '{count} session(s) affected.',
+ affectedAgents: 'Agents using this config: {names}',
+ confirmDelete: 'Delete sandbox backend "{name}"?',
+ confirmDeleteWithAgents: 'Delete sandbox backend "{name}"? {agents}They will fail on their next skill execution.',
+ deleteFailed: 'Failed to delete',
+ deleted: 'Deleted',
+ forceDeleteTitle: 'Sandbox usage cannot be verified',
+ forceDeleteConfirm: 'The backend cannot be reached to verify whether sandboxes remain. If it is gone for good you can force-delete this config; if it is only temporarily unreachable, forcing it leaves any remaining sandboxes with nobody to reclaim them. Force delete anyway?',
+ forceDelete: 'Force delete',
+ disableScripts: 'Disable sandbox execution',
+ enableScripts: 'Enable sandbox execution',
+ disableScriptsConfirm:
+ 'All agents in this workspace — will no longer run skill scripts in a sandbox. They can still read skill content. Existing remote sandboxes are not destroyed automatically; end or delete the related sessions to release them. Continue?',
+ scriptsDisabled: 'Sandbox execution disabled for this workspace',
+ scriptsEnabled: 'Sandbox execution restored for this workspace',
+ policySaveFailed: 'Failed to update sandbox execution policy',
+ legacyConfig: 'Deprecated',
+ namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',
+ fieldRequired: 'Required',
+ cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
+ e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
+ e2bDomainOptional: 'Optional — the SDK default is used when empty',
+ backends: {
+ disabled: 'Disabled',
+ local: 'Local process',
+ docker: 'Docker',
+ cube: 'CubeSandbox',
+ e2b: 'E2B',
+ },
+ apiUrl: 'API endpoint',
+ proxyUrl: 'Proxy endpoint',
+ sandboxDomain: 'Sandbox domain',
+ apiKey: 'API key',
+ templateId: 'Template ID',
+ httpTimeout: 'HTTP timeout (s)',
+ sandboxTtl: 'Sandbox TTL (s)',
+ dockerImage: 'Docker image',
+ defaultTimeout: 'Execution timeout (s)',
+ envVars: 'Environment variables',
+ envKey: 'Name',
+ envValue: 'Value',
+ envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
+ addRow: 'Add variable',
+ removeRow: 'Remove',
+ save: 'Save',
+ saved: 'Saved. Applies to new sessions.',
+ saveFailed: 'Failed to save',
+ testConnection: 'Test connection',
+ deepCheck: 'Full verification',
+ deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',
+ checkPassed: 'All checks passed',
+ checkFailed: 'Some checks failed',
+ noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
+ checks: {
+ client_build: 'Client construction',
+ api_url_reachable: 'Endpoint reachability',
+ credential_valid: 'Credential validity',
+ template_exists: 'Template existence',
+ sandbox_exec: 'In-sandbox execution',
+ egress_available: 'Outbound network',
+ },
+ },
mcpService: 'MCP 서비스',
versionInfo: '버전 정보',
taskQueue: '작업 큐',
@@ -4896,6 +4991,13 @@ export default {
think: '사고',
copy: '복사',
addToKnowledgeBase: '지식베이스에 추가',
+ artifactDrawer: {
+ buttonTitle: '이 응답에서 생성된 파일 다운로드',
+ title: '생성된 파일',
+ empty: '이번 회차에서 다운로드 가능한 파일이 없습니다.',
+ download: '다운로드',
+ downloadFailed: '다운로드에 실패했습니다. 다시 시도해 주세요.',
+ },
updatePlan: '계획 업데이트',
webSearchFound: '<strong>{count}</strong>개의 웹 검색 결과 발견',
toolFallback: '도구',
@@ -5039,6 +5141,15 @@ export default {
selectSkills: 'Skills 선택',
selectSkillsDesc: '활성화할 Skills 선택',
noSkillsAvailable: '사전 설치된 Skills가 없습니다',
+ sandboxConfig: 'Sandbox backend',
+ sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
+ sandboxBackend: 'Sandbox backend',
+ sandboxBackendDefault: 'Use deployment defaults',
+ sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',
+ sandboxBackendMissing: 'Config deleted',
+ sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',
+ sandboxInfoTitle: 'Why choose a backend?',
+ sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',
skillsInfoTitle: 'Skills란 무엇인가요?',
skillsInfoContent: 'Skills는 Agent에 특정 도메인의 지침, 워크플로 및 도구 지원을 제공하는 사전 설치된 전문 지식 모듈입니다. 활성화되면 Agent는 필요할 때 자동으로 관련 지식을 로드합니다.'
},
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 39976459d..e782ae61e 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -4652,6 +4652,101 @@ export default {
vectorStoreEngine: 'Движок векторной БД',
parserEngine: 'Движок парсинга',
storageEngine: 'Движок хранения',
+ sandbox: {
+ title: 'Sandbox Backend',
+ description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',
+ loading: 'Loading sandbox configuration...',
+ loadFailed: 'Failed to load sandbox configuration',
+ backend: 'Sandbox backend',
+ backendHint: 'Leave unset to inherit the global default',
+ addConfig: 'Add sandbox backend',
+ viewDeployDefaults: 'View deployment defaults',
+ deployDefaultsTitle: 'Deployment defaults',
+ deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',
+ deployDefaultBackend: 'Default backend',
+ apiKeyConfigured: 'Configured',
+ apiKeyNotConfigured: 'Not configured',
+ configName: 'Config name',
+ configNamePlaceholder: 'e.g. Production E2B',
+ configNameRequired: 'Please enter a config name',
+ configDescription: 'Description',
+ configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',
+ createTitle: 'Add sandbox backend',
+ editTitle: 'Edit sandbox backend',
+ noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',
+ identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
+ viewSandboxes: 'View sandbox usage',
+ inventoryTitle: 'Sandbox usage',
+ inventoryFailed: 'Failed to load sandbox usage',
+ sandboxCount: 'Sandboxes',
+ sandboxCountUnknown: 'Unknown (backend unreachable)',
+ inventoryUnverifiableHint: 'The backend is unreachable, so the sandbox count is unknown — that is not the same as none.',
+ sandboxesStillLive: 'This config still owns {count} running or paused sandbox(es), so identity fields cannot be changed yet.',
+ blockedHint: 'End or delete those sessions (deleting a session destroys its sandbox), or create a second config and point the agents at it.',
+ unverifiableBlocked: 'The backend cannot be reached to verify whether sandboxes remain, so the stored credentials will not be overwritten.',
+ unverifiableSaveHint: 'Restore connectivity first; if the backend is gone for good, create a second config and point the agents at it.',
+ affectedSessions: '{count} session(s) affected.',
+ affectedAgents: 'Agents using this config: {names}',
+ confirmDelete: 'Delete sandbox backend "{name}"?',
+ confirmDeleteWithAgents: 'Delete sandbox backend "{name}"? {agents}They will fail on their next skill execution.',
+ deleteFailed: 'Failed to delete',
+ deleted: 'Deleted',
+ forceDeleteTitle: 'Sandbox usage cannot be verified',
+ forceDeleteConfirm: 'The backend cannot be reached to verify whether sandboxes remain. If it is gone for good you can force-delete this config; if it is only temporarily unreachable, forcing it leaves any remaining sandboxes with nobody to reclaim them. Force delete anyway?',
+ forceDelete: 'Force delete',
+ disableScripts: 'Disable sandbox execution',
+ enableScripts: 'Enable sandbox execution',
+ disableScriptsConfirm:
+ 'All agents in this workspace — will no longer run skill scripts in a sandbox. They can still read skill content. Existing remote sandboxes are not destroyed automatically; end or delete the related sessions to release them. Continue?',
+ scriptsDisabled: 'Sandbox execution disabled for this workspace',
+ scriptsEnabled: 'Sandbox execution restored for this workspace',
+ policySaveFailed: 'Failed to update sandbox execution policy',
+ legacyConfig: 'Deprecated',
+ namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',
+ fieldRequired: 'Required',
+ cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
+ e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
+ e2bDomainOptional: 'Optional — the SDK default is used when empty',
+ backends: {
+ disabled: 'Disabled',
+ local: 'Local process',
+ docker: 'Docker',
+ cube: 'CubeSandbox',
+ e2b: 'E2B',
+ },
+ apiUrl: 'API endpoint',
+ proxyUrl: 'Proxy endpoint',
+ sandboxDomain: 'Sandbox domain',
+ apiKey: 'API key',
+ templateId: 'Template ID',
+ httpTimeout: 'HTTP timeout (s)',
+ sandboxTtl: 'Sandbox TTL (s)',
+ dockerImage: 'Docker image',
+ defaultTimeout: 'Execution timeout (s)',
+ envVars: 'Environment variables',
+ envKey: 'Name',
+ envValue: 'Value',
+ envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
+ addRow: 'Add variable',
+ removeRow: 'Remove',
+ save: 'Save',
+ saved: 'Saved. Applies to new sessions.',
+ saveFailed: 'Failed to save',
+ testConnection: 'Test connection',
+ deepCheck: 'Full verification',
+ deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',
+ checkPassed: 'All checks passed',
+ checkFailed: 'Some checks failed',
+ noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
+ checks: {
+ client_build: 'Client construction',
+ api_url_reachable: 'Endpoint reachability',
+ credential_valid: 'Credential validity',
+ template_exists: 'Template existence',
+ sandbox_exec: 'In-sandbox execution',
+ egress_available: 'Outbound network',
+ },
+ },
mcpService: 'Сервис MCP',
versionInfo: 'Информация о версии',
taskQueue: 'Очереди задач',
@@ -4896,6 +4991,13 @@ export default {
think: 'Размышление',
copy: 'Копировать',
addToKnowledgeBase: 'Добавить в базу знаний',
+ artifactDrawer: {
+ buttonTitle: 'Скачать файлы, сгенерированные в этом ответе',
+ title: 'Сгенерированные файлы',
+ empty: 'В этом раунде не создано файлов для скачивания.',
+ download: 'Скачать',
+ downloadFailed: 'Не удалось скачать, повторите попытку.',
+ },
updatePlan: 'Обновить план',
webSearchFound: 'Найдено <strong>{count}</strong> результатов веб‑поиска',
toolFallback: 'Инструмент',
@@ -5039,6 +5141,15 @@ export default {
selectSkills: 'Выбрать Skills',
selectSkillsDesc: 'Выберите Skills для активации',
noSkillsAvailable: 'Нет доступных предустановленных Skills',
+ sandboxConfig: 'Sandbox backend',
+ sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
+ sandboxBackend: 'Sandbox backend',
+ sandboxBackendDefault: 'Use deployment defaults',
+ sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',
+ sandboxBackendMissing: 'Config deleted',
+ sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',
+ sandboxInfoTitle: 'Why choose a backend?',
+ sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',
skillsInfoTitle: 'Что такое Skills?',
skillsInfoContent: 'Skills — это предустановленные модули профессиональных знаний, которые предоставляют агенту инструкции, рабочие процессы и инструменты для конкретных областей. При активации агент автоматически загружает соответствующие знания по мере необходимости.'
},
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index f2f274e7e..d45df800f 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -4652,6 +4652,101 @@ export default {
vectorStoreEngine: '向量数据库引擎',
parserEngine: '解析引擎',
storageEngine: '存储引擎',
+ sandbox: {
+ title: '沙箱后端',
+ description: '配置多份沙箱后端,智能体可各自选用其中一份。未填写的项沿用 .env 中的全局默认值。',
+ loading: '加载沙箱配置...',
+ loadFailed: '加载沙箱配置失败',
+ backend: '沙箱后端',
+ backendHint: '留空表示沿用全局默认',
+ addConfig: '添加沙箱后端',
+ viewDeployDefaults: '查看部署默认配置',
+ deployDefaultsTitle: '部署默认配置',
+ deployDefaultsHint: '来自 .env 的全局配置。配置里留空的项即沿用这里的值。',
+ deployDefaultBackend: '默认后端',
+ apiKeyConfigured: '已配置',
+ apiKeyNotConfigured: '未配置',
+ configName: '配置名称',
+ configNamePlaceholder: '如:生产 E2B',
+ configNameRequired: '请填写配置名称',
+ configDescription: '描述',
+ configDescriptionPlaceholder: '选填,用于区分多份同类型配置',
+ createTitle: '添加沙箱后端',
+ editTitle: '编辑沙箱后端',
+ noConfigs: '还没有沙箱后端配置。智能体将使用部署默认配置运行技能脚本。',
+ identityFieldHint: '该配置下有沙箱运行时,以下项无法修改:后端类型、API 端点、API Key、沙箱域名、Proxy 端点。',
+ viewSandboxes: '查看沙箱占用',
+ inventoryTitle: '沙箱占用',
+ inventoryFailed: '获取沙箱占用失败',
+ sandboxCount: '沙箱数量',
+ sandboxCountUnknown: '未知(无法连接该后端)',
+ inventoryUnverifiableHint: '无法连接该后端,因此沙箱数量未知——这不代表没有沙箱。',
+ sandboxesStillLive: '该配置仍有 {count} 个运行中或已暂停的沙箱,暂时无法修改身份字段。',
+ blockedHint: '可结束或删除这些会话(删除会话会销毁其沙箱),或新建一份配置并把智能体指过去。',
+ unverifiableBlocked: '无法连接该后端核实是否仍有沙箱,因此不能覆盖现有凭据。',
+ unverifiableSaveHint: '请先恢复该后端的连通性;若已废弃,可新建一份配置并把智能体指过去。',
+ affectedSessions: '影响 {count} 个会话。',
+ affectedAgents: '以下智能体正在使用该配置:{names}',
+ confirmDelete: '确定删除沙箱后端「{name}」吗?',
+ confirmDeleteWithAgents: '确定删除沙箱后端「{name}」吗?{agents}它们将在下次执行技能时报错。',
+ deleteFailed: '删除失败',
+ deleted: '已删除',
+ forceDeleteTitle: '无法核实沙箱占用',
+ forceDeleteConfirm: '无法连接该后端核实是否仍有沙箱。若该后端已废弃,可强制删除这份配置;若只是暂时不可达,强制删除会让残留沙箱无人回收。仍要强制删除吗?',
+ forceDelete: '强制删除',
+ disableScripts: '禁用沙盒执行',
+ enableScripts: '启用沙盒执行',
+ disableScriptsConfirm:
+ '禁用后,本空间内所有智能体将无法在沙盒中执行技能脚本;仍可阅读技能内容。已在运行中的远端沙盒不会自动销毁,需结束或删除相关会话后才会释放。是否继续?',
+ scriptsDisabled: '已禁用本空间沙盒执行',
+ scriptsEnabled: '已恢复本空间沙盒执行',
+ policySaveFailed: '更新沙盒执行策略失败',
+ legacyConfig: '已废弃',
+ namedBackendHint: '具名配置支持 CubeSandbox 与 E2B。',
+ fieldRequired: '必填',
+ cubeApiKeyOptional: '可留空 —— 自建 CubeSandbox 通常无鉴权',
+ e2bApiUrlOptional: '可留空 —— 留空时使用 SDK 默认值',
+ e2bDomainOptional: '可留空 —— 留空时使用 SDK 默认值',
+ backends: {
+ disabled: '禁用',
+ local: '本地进程',
+ docker: 'Docker',
+ cube: 'CubeSandbox',
+ e2b: 'E2B',
+ },
+ apiUrl: 'API 端点',
+ proxyUrl: 'Proxy 端点',
+ sandboxDomain: '沙箱域名',
+ apiKey: 'API Key',
+ templateId: '模板 ID',
+ httpTimeout: 'HTTP 超时(秒)',
+ sandboxTtl: '沙箱 TTL(秒)',
+ dockerImage: 'Docker 镜像',
+ defaultTimeout: '执行超时(秒)',
+ envVars: '环境变量',
+ envKey: '变量名',
+ envValue: '变量值',
+ envVarsHint: '注入到该空间所有沙箱;值加密存储,但对沙箱内脚本可见,请勿放入脚本不应读取的密钥。',
+ addRow: '添加变量',
+ removeRow: '删除',
+ save: '保存',
+ saved: '已保存,对新建会话生效',
+ saveFailed: '保存失败',
+ testConnection: '测试连接',
+ deepCheck: '完整验证',
+ deepCheckConfirm: '完整验证会真实创建并销毁一个沙箱,消耗少量沙箱时长,是否继续?',
+ checkPassed: '检测通过',
+ checkFailed: '检测未通过',
+ noVolumeSupport: '该后端不支持挂载卷,依赖共享卷的技能将不可用。',
+ checks: {
+ client_build: '客户端构建',
+ api_url_reachable: '端点可达性',
+ credential_valid: '凭据有效性',
+ template_exists: '模板存在性',
+ sandbox_exec: '沙箱内执行',
+ egress_available: '出网可用',
+ },
+ },
mcpService: 'MCP服务',
versionInfo: '版本信息',
taskQueue: '任务队列',
@@ -4896,6 +4991,13 @@ export default {
think: '思考',
copy: '复制',
addToKnowledgeBase: '添加到知识库',
+ artifactDrawer: {
+ buttonTitle: '下载本次生成的文件',
+ title: '生成的文件',
+ empty: '本次未生成可下载的文件',
+ download: '下载',
+ downloadFailed: '下载失败,请稍后重试',
+ },
updatePlan: '更新计划',
webSearchFound: '找到 <strong>{count}</strong> 个网络搜索结果',
toolFallback: '工具',
@@ -5039,6 +5141,15 @@ export default {
selectSkills: '选择 Skills',
selectSkillsDesc: '选择要启用的 Skills',
noSkillsAvailable: '暂无预装 Skills',
+ sandboxConfig: '沙箱后端',
+ sandboxConfigDesc: '选择该智能体的技能脚本在哪个沙箱后端中执行。',
+ sandboxBackend: '沙箱后端',
+ sandboxBackendDefault: '使用部署默认配置',
+ sandboxBackendHint: '仅在启用技能执行时生效。所选配置被删除后,该智能体的技能执行会失败。',
+ sandboxBackendMissing: '配置已删除',
+ sandboxNoConfigs: '当前空间还没有具名沙箱后端配置,技能脚本将运行在部署默认配置上。可在「设置 - 沙箱后端」中添加。',
+ sandboxInfoTitle: '为什么要选后端?',
+ sandboxInfoContent: '不同后端对应不同的账号、区域与配额。同一会话的沙箱一旦创建,后续的附件、产物与销毁都会锁定在创建时那份配置上,改这里只影响之后新建的沙箱。',
skillsInfoTitle: '什么是 Skills?',
skillsInfoContent: 'Skills 是预装的专业知识模块,可以为 Agent 提供特定领域的指令、工作流程和工具支持。启用 Skills 后,Agent 会在需要时自动加载相关知识。'
},
diff --git a/frontend/src/stores/chatResources.ts b/frontend/src/stores/chatResources.ts
index 0bd51bda5..20916412c 100644
--- a/frontend/src/stores/chatResources.ts
+++ b/frontend/src/stores/chatResources.ts
@@ -4,12 +4,13 @@ import { listKnowledgeBases, getKnowledgeBaseById } from '@/api/knowledge-base'
import { listAgents, type CustomAgent } from '@/api/agent'
import { listModels, type ModelConfig } from '@/api/model'
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider'
+import { isNamedSandboxBackend, listSandboxConfigs, type SandboxConfigRecord } from '@/api/system'
import { useOrganizationStore } from '@/stores/organization'
/** 空间级资源缓存 TTL */
const CACHE_TTL_MS = 60_000
-type ResourceKey = 'knowledgeBases' | 'agents' | 'models' | 'webSearchProviders'
+type ResourceKey = 'knowledgeBases' | 'agents' | 'models' | 'webSearchProviders' | 'sandboxConfigs'
export type ListCreatorFilter = 'all' | 'mine' | 'others'
@@ -27,6 +28,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
const disabledOwnAgentIds = ref<string[]>([])
const allModels = ref<ModelConfig[]>([])
const webSearchProviders = ref<WebSearchProviderEntity[]>([])
+ const sandboxConfigs = ref<SandboxConfigRecord[]>([])
const loadedAt = ref<Partial<Record<ResourceKey, number>>>({})
const inflight = new Map<ResourceKey, Promise<void>>()
@@ -174,6 +176,30 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
})
}
+ /**
+ * 沙箱后端配置,供智能体编辑器的后端选择器使用。
+ *
+ * 不进 prefetchChatInput:只有编辑智能体时才需要,而对话输入栏用不到,
+ * 没必要让每次首屏都多打一次请求。
+ *
+ * 失败只吞掉不抛:这是可选资源——拿不到就只剩「使用部署默认配置」一项,
+ * 智能体照样能编辑保存。调用方通常把它和一堆必需资源放在同一个
+ * Promise.all 里,若在这里抛出,整个编辑器的依赖加载都会连坐
+ * (技能可用性拿不到 ⇒ 技能配置分组直接消失)。
+ */
+ async function ensureSandboxConfigs(force = false): Promise<void> {
+ return runOnce('sandboxConfigs', force, async () => {
+ try {
+ const res = await listSandboxConfigs()
+ const rows = Array.isArray(res?.data) ? res.data : []
+ sandboxConfigs.value = rows.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type))
+ } catch {
+ sandboxConfigs.value = []
+ }
+ loadedAt.value.sandboxConfigs = Date.now()
+ })
+ }
+
/** 并行预取对话输入栏及列表页常用的空间级资源 */
async function prefetchChatInput(force = false): Promise<void> {
const orgStore = useOrganizationStore()
@@ -258,6 +284,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
disabledOwnAgentIds.value = []
allModels.value = []
webSearchProviders.value = []
+ sandboxConfigs.value = []
agentKbCache.clear()
// 同时丢弃所有 inflight 句柄,否则失效后仍在飞行的请求会把旧数据写回缓存。
inflight.clear()
@@ -290,6 +317,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
allModels,
chatModels,
webSearchProviders,
+ sandboxConfigs,
isFresh,
fetchKnowledgeBasesForList,
fetchAgentsForList,
@@ -298,6 +326,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
ensureModels,
ensureChatModels,
ensureWebSearchProviders,
+ ensureSandboxConfigs,
ensureAgentKnowledgeBases,
prefetchChatInput,
fetchKnowledgeBaseById,
diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue
index c16671392..94e6c15d6 100644
--- a/frontend/src/views/agent/AgentEditorModal.vue
+++ b/frontend/src/views/agent/AgentEditorModal.vue
@@ -1289,6 +1289,46 @@
</div>
</div>
+ <!-- 沙箱后端配置(仅 Agent 模式):技能脚本的运行环境 -->
+ <div v-show="currentSection === 'sandbox' && isAgentMode" class="section">
+ <div class="section-header">
+ <h2>{{ $t('agent.editor.sandboxConfig') }}</h2>
+ <p class="section-description">{{ $t('agent.editor.sandboxConfigDesc') }}</p>
+ </div>
+
+ <div class="settings-group">
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ $t('agent.editor.sandboxBackend') }}</label>
+ <p class="desc">{{ $t('agent.editor.sandboxBackendHint') }}</p>
+ </div>
+ <div class="setting-control">
+ <t-select v-model="formData.config.sandbox_config_id"
+ :placeholder="$t('agent.editor.sandboxBackendDefault')" style="width: 280px">
+ <t-option value="" :label="$t('agent.editor.sandboxBackendDefault')" />
+ <t-option v-for="cfg in sandboxConfigOptions" :key="cfg.id" :value="cfg.id"
+ :label="`${cfg.name} (${backendLabel(cfg.sandbox_type)})`" />
+ </t-select>
+ </div>
+ </div>
+
+ <!-- 未建具名配置时说明「默认」到底是什么,避免下拉只有一项时显得像坏了 -->
+ <div v-if="sandboxConfigOptions.length === 0" class="setting-row">
+ <div class="setting-info">
+ <p class="desc empty-hint">{{ $t('agent.editor.sandboxNoConfigs') }}</p>
+ </div>
+ </div>
+
+ <div class="skill-info-box">
+ <t-icon name="cloud" class="info-icon" />
+ <div class="info-content">
+ <p><strong>{{ $t('agent.editor.sandboxInfoTitle') }}</strong></p>
+ <p>{{ $t('agent.editor.sandboxInfoContent') }}</p>
+ </div>
+ </div>
+ </div>
+ </div>
+
<!-- 知识库配置 -->
<div v-show="currentSection === 'knowledge'" class="section">
<div class="section-header">
@@ -1665,7 +1705,13 @@ import { type ModelConfig } from '@/api/model';
import { type AgentNotReadyReasonKey, agentRequiresRerankModel } from '@/utils/agent-readiness';
import { type SkillInfo } from '@/api/skill';
import { type WebSearchProviderEntity } from '@/api/web-search-provider';
-import { type StorageEngineStatusItem, type PromptTemplate, type PromptTemplatesConfig } from '@/api/system';
+import {
+ isNamedSandboxBackend,
+ type SandboxConfigRecord,
+ type StorageEngineStatusItem,
+ type PromptTemplate,
+ type PromptTemplatesConfig,
+} from '@/api/system';
import { useUIStore } from '@/stores/ui';
import { useAuthStore } from '@/stores/auth';
import { useOrganizationStore } from '@/stores/organization';
@@ -1885,6 +1931,19 @@ const webSearchProviderList = ref<WebSearchProviderEntity[]>([]);
const skillOptions = ref<{ name: string; description: string }[]>([]);
// 是否允许启用 Skills(取决于后端沙箱是否启用,disabled 时为 false;未请求前为 false 避免闪显)
const skillsAvailable = ref(false);
+// 空间内的具名沙箱后端配置。始终包含当前已选中的那份,即使它已被删除——
+// 否则下拉会静默显示为"使用部署默认配置",看不出该智能体其实指着一份不存在的配置。
+const sandboxConfigOptions = computed(() => {
+ const configs = chatResources.sandboxConfigs.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type));
+ const selected = formData.value.config.sandbox_config_id;
+ if (!selected || configs.some((cfg) => cfg.id === selected)) return configs;
+ return [
+ ...configs,
+ { id: selected, name: t('agent.editor.sandboxBackendMissing'), sandbox_type: '' } as SandboxConfigRecord,
+ ];
+});
+const backendLabel = (type: string) =>
+ type ? t(`settings.sandbox.backends.${type}`) : t('common.error');
// 存储引擎可用状态(用于图片存储 provider 选择)
const storageEngineStatus = ref<StorageEngineStatusItem[]>([]);
const imageStorageOptions = computed(() => {
@@ -2248,6 +2307,9 @@ const navItems = computed(() => {
}
if (isAgentMode.value && skillsAvailable.value) {
items.push({ key: 'skills', icon: 'lightbulb', label: t('agent.editor.skillsConfig') });
+ // 沙箱是技能脚本的运行环境:先选跑哪些技能,再选跑在哪份后端上。
+ // 与 skills 同门控——部署级沙箱关闭时技能整体不可用,选后端也就无从谈起。
+ items.push({ key: 'sandbox', icon: 'cloud', label: t('agent.editor.sandboxConfig') });
}
// 发布(仅编辑模式)
if (editorMode.value === 'edit' && editorAgent.value?.id && !editorAgent.value?.is_builtin && !authStore.isLiteMode) {
@@ -2275,7 +2337,7 @@ const navGroups = computed(() => {
{
key: 'capability',
label: t('agentEditor.navGroups.capability'),
- items: pickItems(['multimodal', 'tools', 'mcp', 'skills']),
+ items: pickItems(['multimodal', 'tools', 'mcp', 'skills', 'sandbox']),
},
{
key: 'integration',
@@ -2315,6 +2377,8 @@ const defaultFormData = {
// Skills 设置
skills_selection_mode: 'none' as 'all' | 'selected' | 'none',
selected_skills: [] as string[],
+ // 技能脚本运行在哪份沙箱后端配置上。留空表示使用部署默认配置。
+ sandbox_config_id: '' as string,
// 知识库设置:新建智能体默认选择 "全部知识库",
// 让用户无需先去勾选 KB 即可上手;如有需要可改为 "selected" / "none"。
kb_selection_mode: 'all' as 'all' | 'selected' | 'none',
@@ -3345,6 +3409,7 @@ const loadDependencies = async () => {
chatResources.ensureModels(),
chatResources.ensureKnowledgeBases(),
chatResources.ensureWebSearchProviders(),
+ chatResources.ensureSandboxConfigs(),
editorResources.prefetchAgentEditorDeps(),
]);
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index 34284fde3..7372a441d 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -315,6 +315,23 @@
:title="$t('agent.addToKnowledgeBase')">
<t-icon name="bookmark-add" />
</t-button>
+ <!-- Skill artifact download: only shown when the persisted
+ assistant message recorded any generated files. Agent
+ mode is the primary path for skills, so this is where
+ the button is most likely to appear. -->
+ <t-badge
+ v-if="hasArtifacts"
+ :count="artifactCount"
+ :offset="[-4, 4]"
+ shape="round"
+ size="small"
+ >
+ <t-button size="small" variant="outline" shape="round"
+ @click.stop="openArtifactDrawer"
+ :title="$t('agent.artifactDrawer.buttonTitle')">
+ <t-icon name="download" />
+ </t-button>
+ </t-badge>
<t-tooltip v-if="event.is_fallback" :content="$t('chat.fallbackHint')" placement="top">
<t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">
<t-icon name="info-circle" />
@@ -479,6 +496,13 @@
</div>
</template>
</t-drawer>
+ <ChatArtifactsDrawer
+ v-if="hasArtifacts && sessionIdForArtifacts && messageIdForArtifacts"
+ v-model:visible="showArtifactDrawer"
+ :session-id="sessionIdForArtifacts"
+ :message-id="messageIdForArtifacts"
+ :artifacts="artifactList"
+ />
</template>
<script setup lang="ts">
@@ -492,6 +516,7 @@ import McpOAuthCard from './McpOAuthCard.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
+import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';
import { countGrepDocuments, groupGrepChunkResults } from '@/utils/grepResultsGroup';
import { getKnowledgeChunksSummaryHtml } from '@/utils/knowledgeChunksDisplay';
import { getAttachmentParsingSummaryHtml } from '@/utils/attachmentParsingDisplay';
@@ -856,6 +881,30 @@ watch(
},
);
+// -----------------------------------------------------------------------------
+// Skill artifact download drawer (Agent path)
+// -----------------------------------------------------------------------------
+// Same contract as botmsg.vue: only render the button when the persisted
+// assistant message actually recorded files, then let ChatArtifactsDrawer
+// resolve names/sizes/mtimes and stream downloads via the /artifacts
+// endpoint. Agent mode is the primary path for skills, so this button will
+// appear more often here than in the RAG path.
+const showArtifactDrawer = ref(false);
+const artifactList = computed(() => {
+ const list = ((props.session?.artifacts as any[]) || []);
+ return list.map((a, i) => ({ index: i, ...a }));
+});
+const hasArtifacts = computed(() => artifactList.value.length > 0);
+const artifactCount = computed(() => artifactList.value.length);
+const sessionIdForArtifacts = computed(() => props.sessionId ?? '');
+const messageIdForArtifacts = computed(() =>
+ String(props.session?.id || props.session?.request_id || ''),
+);
+function openArtifactDrawer() {
+ if (!hasArtifacts.value) return;
+ showArtifactDrawer.value = true;
+}
+
const {
float: citationFloat,
rebind: rebindCitations,
diff --git a/frontend/src/views/chat/components/ChatArtifactsDrawer.vue b/frontend/src/views/chat/components/ChatArtifactsDrawer.vue
new file mode 100644
index 000000000..76cdb4b69
--- /dev/null
+++ b/frontend/src/views/chat/components/ChatArtifactsDrawer.vue
@@ -0,0 +1,307 @@
+<template>
+ <!--
+ ChatArtifactsDrawer — right-side drawer that lists every skill-generated
+ file attached to the surrounding assistant message.
+
+ Usage (from botmsg.vue / AgentStreamDisplay.vue):
+ <ChatArtifactsDrawer
+ v-model:visible="showArtifacts"
+ :session-id="sessionId"
+ :message-id="messageId"
+ :artifacts="artifacts"
+ />
+
+ The list is driven by whatever the parent has already resolved from
+ the streamed message payload. When the parent has no local copy
+ (e.g. after a page refresh) it can pass an empty array and the
+ drawer will pull the metadata itself via /artifacts.
+ -->
+ <t-drawer
+ v-model:visible="internalVisible"
+ placement="right"
+ size="440px"
+ attach="body"
+ :header="$t('agent.artifactDrawer.title')"
+ :footer="false"
+ :close-on-overlay-click="true"
+ :destroy-on-close="false"
+ @close="handleClose"
+ >
+ <div v-if="loading" class="artifact-drawer-empty">
+ <t-loading size="small" />
+ <span>{{ $t('common.loading') }}</span>
+ </div>
+ <div v-else-if="!items.length" class="artifact-drawer-empty">
+ <t-icon name="folder-open" size="32" />
+ <span>{{ $t('agent.artifactDrawer.empty') }}</span>
+ </div>
+ <t-list v-else split :size="'medium'">
+ <t-list-item v-for="item in items" :key="`${item.index}-${item.file_name}`" class="artifact-item">
+ <div class="artifact-icon">
+ <t-icon :name="iconForFile(item.file_name)" size="24" />
+ </div>
+ <div class="artifact-body">
+ <div class="artifact-name" :title="item.file_name">{{ item.file_name }}</div>
+ <div class="artifact-meta">
+ <span>{{ formatFileSize(item.file_size) }}</span>
+ <span class="artifact-meta-sep">·</span>
+ <span>{{ formatDateTime(item.created_at) }}</span>
+ </div>
+ </div>
+ <t-button
+ size="small"
+ variant="outline"
+ shape="round"
+ :loading="!!downloading[item.index]"
+ @click.stop="handleDownload(item)"
+ >
+ <t-icon name="download" />
+ <span class="artifact-download-label">
+ {{ $t('agent.artifactDrawer.download') }}
+ </span>
+ </t-button>
+ </t-list-item>
+ </t-list>
+ </t-drawer>
+</template>
+
+<script setup lang="ts">
+/*
+ * Design notes:
+ * - The drawer is stateless w.r.t. the download itself; it delegates to
+ * the chat API's downloadArtifact() helper which uses the axios blob
+ * transport (getDown) so the Bearer token stays attached — plain
+ * <a href> would drop it and hit 401.
+ * - `items` prefers the props-provided list (already in memory from the
+ * stream payload). When empty, we pull from /artifacts on open so a
+ * refreshed page still shows something without waiting for the parent
+ * to re-hydrate.
+ * - Errors during download are surfaced via MessagePlugin.error but do
+ * NOT close the drawer, matching spec §7: "抽屉保持打开以便重试其他文件".
+ */
+import { computed, ref, watch, reactive } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { MessagePlugin } from 'tdesign-vue-next'
+import { downloadArtifact, listMessageArtifacts, type ArtifactMeta } from '@/api/chat'
+
+const props = defineProps<{
+ visible: boolean
+ sessionId: string
+ messageId: string
+ artifacts?: ArtifactMeta[]
+}>()
+
+const emit = defineEmits<{
+ (e: 'update:visible', v: boolean): void
+}>()
+
+const { t } = useI18n()
+
+// Two-way binding shim so `v-model:visible` works while the parent still
+// owns the source of truth.
+const internalVisible = computed({
+ get: () => props.visible,
+ set: (v: boolean) => emit('update:visible', v),
+})
+
+const loading = ref(false)
+const fetched = ref<ArtifactMeta[]>([])
+const downloading = reactive<Record<number, boolean>>({})
+
+const items = computed<ArtifactMeta[]>(() => {
+ if (props.artifacts && props.artifacts.length) return props.artifacts
+ return fetched.value
+})
+
+// Refresh /artifacts when the drawer opens without a caller-provided list.
+// Cheap when the caller already passed artifacts; a real request only when
+// the parent's copy is empty (e.g. right after page refresh, before message
+// hydration finishes).
+watch(
+ () => props.visible,
+ async (open) => {
+ if (!open) return
+ if (props.artifacts && props.artifacts.length) {
+ fetched.value = []
+ return
+ }
+ if (!props.sessionId || !props.messageId) return
+ loading.value = true
+ try {
+ const res: any = await listMessageArtifacts(props.sessionId, props.messageId)
+ const data = (res && (res.data || res)) as ArtifactMeta[] | undefined
+ fetched.value = Array.isArray(data) ? data : []
+ } catch (err) {
+ console.error('[ChatArtifactsDrawer] load failed:', err)
+ fetched.value = []
+ } finally {
+ loading.value = false
+ }
+ },
+)
+
+function handleClose() {
+ emit('update:visible', false)
+}
+
+// Format helpers.
+function formatFileSize(size: number): string {
+ if (!size || size < 0) return '0 B'
+ const units = ['B', 'KB', 'MB', 'GB']
+ let s = size
+ let unit = 0
+ while (s >= 1024 && unit < units.length - 1) {
+ s /= 1024
+ unit++
+ }
+ // Keep one decimal for non-integer units; integers stay integer.
+ return unit === 0 ? `${s} ${units[unit]}` : `${s.toFixed(1)} ${units[unit]}`
+}
+
+function formatDateTime(raw: string): string {
+ if (!raw) return '—'
+ const d = new Date(raw)
+ if (Number.isNaN(d.getTime())) return raw
+ // Local time, seconds precision — matches how the rest of the app
+ // renders message timestamps.
+ const pad = (n: number) => String(n).padStart(2, '0')
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
+}
+
+function iconForFile(name: string): string {
+ const ext = (name.split('.').pop() || '').toLowerCase()
+ switch (ext) {
+ case 'pptx':
+ case 'ppt':
+ return 'chart-pie'
+ case 'xlsx':
+ case 'xls':
+ case 'csv':
+ return 'file-excel'
+ case 'docx':
+ case 'doc':
+ return 'file-word'
+ case 'pdf':
+ return 'file-pdf'
+ case 'md':
+ case 'markdown':
+ return 'file'
+ case 'html':
+ case 'htm':
+ return 'code-1'
+ case 'json':
+ return 'code-1'
+ case 'png':
+ case 'jpg':
+ case 'jpeg':
+ case 'gif':
+ case 'svg':
+ case 'webp':
+ return 'image'
+ case 'mp3':
+ case 'wav':
+ case 'ogg':
+ return 'sound-up'
+ case 'mp4':
+ case 'mov':
+ case 'webm':
+ return 'video'
+ case 'zip':
+ case 'tar':
+ case 'gz':
+ return 'folder-zip'
+ default:
+ return 'file-attachment'
+ }
+}
+
+async function handleDownload(item: ArtifactMeta) {
+ if (!props.sessionId || !props.messageId) {
+ MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
+ return
+ }
+ downloading[item.index] = true
+ try {
+ const blob = await downloadArtifact(props.sessionId, props.messageId, item.index)
+ // Trigger browser save via an object URL so the file name comes
+ // through even when the server's Content-Disposition is stripped
+ // by an intermediate proxy.
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = item.file_name || 'artifact'
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ // Give the browser a tick to start the download before revoking.
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
+ } catch (err) {
+ console.error('[ChatArtifactsDrawer] download failed:', err)
+ MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
+ } finally {
+ downloading[item.index] = false
+ }
+}
+</script>
+
+<style lang="less" scoped>
+.artifact-drawer-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 48px 16px;
+ color: var(--td-text-color-placeholder);
+ font-size: 13px;
+}
+
+.artifact-item {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 8px 4px;
+
+ .artifact-icon {
+ flex-shrink: 0;
+ width: 36px;
+ height: 36px;
+ border-radius: 8px;
+ background: var(--td-bg-color-container-hover);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--td-brand-color);
+ }
+
+ .artifact-body {
+ flex: 1;
+ min-width: 0;
+ }
+
+ .artifact-name {
+ font-size: 14px;
+ color: var(--td-text-color-primary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ .artifact-meta {
+ margin-top: 2px;
+ font-size: 12px;
+ color: var(--td-text-color-placeholder);
+ display: flex;
+ gap: 4px;
+ align-items: center;
+ }
+
+ .artifact-meta-sep {
+ opacity: 0.6;
+ }
+
+ .artifact-download-label {
+ margin-left: 4px;
+ }
+}
+</style>
diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue
index f696550fc..38fa5899f 100644
--- a/frontend/src/views/chat/components/botmsg.vue
+++ b/frontend/src/views/chat/components/botmsg.vue
@@ -46,6 +46,23 @@
:title="$t('agent.addToKnowledgeBase')">
<t-icon name="bookmark-add" />
</t-button>
+ <!-- Skill artifact download: only shown when this reply's
+ assistant message actually recorded any generated files.
+ Emptiness is the default: the button stays hidden for
+ conversational messages that never touched a skill. -->
+ <t-badge
+ v-if="hasArtifacts"
+ :count="artifactCount"
+ :offset="[-4, 4]"
+ shape="round"
+ size="small"
+ >
+ <t-button size="small" variant="outline" shape="round"
+ @click.stop="openArtifactDrawer"
+ :title="$t('agent.artifactDrawer.buttonTitle')">
+ <t-icon name="download" />
+ </t-button>
+ </t-badge>
<!-- Fallback 提示图标 -->
<t-tooltip v-if="session.is_fallback" :content="$t('chat.fallbackHint')" placement="top">
<t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">
@@ -69,6 +86,13 @@
<ChatCitationFloat :float="citationFloat" :on-enter="cancelCitationClose"
:on-leave="scheduleCitationClose" />
</Teleport>
+ <ChatArtifactsDrawer
+ v-if="hasArtifacts"
+ v-model:visible="showArtifactDrawer"
+ :session-id="sessionId"
+ :message-id="messageIdForArtifacts"
+ :artifacts="artifactList"
+ />
</div>
</template>
<script setup>
@@ -81,6 +105,7 @@ import RagPipelineProgress from './RagPipelineProgress.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
+import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';
import { sanitizeMarkdownHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security';
import { useI18n } from 'vue-i18n';
import { MessagePlugin } from 'tdesign-vue-next';
@@ -165,6 +190,40 @@ const props = defineProps({
const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
+// -----------------------------------------------------------------------------
+// Skill artifact download (drawer)
+// -----------------------------------------------------------------------------
+// The download button and drawer are opt-in per message: the toolbar checks
+// `hasArtifacts` and only renders when the assistant message actually
+// recorded a file. `messageIdForArtifacts` resolves to whichever field the
+// caller uses to identify the row on the server (session.id from the SSE
+// hydration path, request_id when the caller pre-populated it).
+//
+// NOTE: this file's <script setup> block is plain JS (no lang="ts"), so we
+// stay away from TypeScript-only syntax like `as any[]` — the vite Vue
+// plugin routes non-TS blocks through babel which rejects those tokens.
+const showArtifactDrawer = ref(false);
+const artifactList = computed(() => {
+ const raw = props.session && props.session.artifacts;
+ const list = Array.isArray(raw) ? raw : [];
+ // Enrich each entry with its position so the download endpoint can
+ // resolve it. Server responses already include `index` when they come
+ // via listMessageArtifacts; SSE payloads that land through Message.Artifacts
+ // omit it. Normalising here keeps ChatArtifactsDrawer index-agnostic.
+ return list.map((a, i) => ({ index: i, ...a }));
+});
+const hasArtifacts = computed(() => artifactList.value.length > 0);
+const artifactCount = computed(() => artifactList.value.length);
+const messageIdForArtifacts = computed(() => {
+ // Prefer the persistent message ID; fall back to request_id for the
+ // in-flight path where the SSE stream still identifies rows by request.
+ return String((props.session && (props.session.id || props.session.request_id)) || '');
+});
+function openArtifactDrawer() {
+ if (!hasArtifacts.value) return;
+ showArtifactDrawer.value = true;
+}
+
const preview = (url) => {
nextTick(() => {
reviewUrl.value = url;
diff --git a/frontend/src/views/settings/SandboxSettings.vue b/frontend/src/views/settings/SandboxSettings.vue
new file mode 100644
index 000000000..90c198b90
--- /dev/null
+++ b/frontend/src/views/settings/SandboxSettings.vue
@@ -0,0 +1,706 @@
+<template>
+ <div class="sandbox-settings">
+ <div class="section-header">
+ <div class="section-header__top">
+ <div>
+ <h2>{{ $t('settings.sandbox.title') }}</h2>
+ <p class="section-description">{{ $t('settings.sandbox.description') }}</p>
+ <p class="section-description section-description--hint">{{ $t('settings.sandbox.namedBackendHint') }}</p>
+ </div>
+ <t-button theme="primary" variant="text" size="medium" class="defaults-trigger" @click="showDefaults = true">
+ <template #icon><t-icon name="info-circle" /></template>
+ {{ $t('settings.sandbox.viewDeployDefaults') }}
+ </t-button>
+ </div>
+ </div>
+
+ <div class="sandbox-tabs-row">
+ <t-tabs v-model="activeType" class="sandbox-type-tabs">
+ <t-tab-panel value="all" :label="`${$t('common.all')}(${records.length})`" />
+ <t-tab-panel v-for="type in backendTypes" :key="type" :value="type"
+ :label="`${backendLabel(type)}(${countByType(type)})`" />
+ </t-tabs>
+ <div class="sandbox-tabs-actions">
+ <t-button v-if="!workspaceScriptsDisabled" variant="outline" theme="danger" size="medium"
+ :loading="policySaving" @click="confirmDisableScripts">
+ {{ $t('settings.sandbox.disableScripts') }}
+ </t-button>
+ <t-button v-else variant="outline" theme="primary" size="medium" :loading="policySaving"
+ @click="enableScripts">
+ {{ $t('settings.sandbox.enableScripts') }}
+ </t-button>
+ </div>
+ </div>
+
+ <t-loading :loading="loading" size="small" class="sandbox-list-loading">
+ <div v-if="!loading" class="sandbox-grid">
+ <div v-for="record in filteredRecords" :key="record.id" class="sandbox-card"
+ :class="`sandbox-card--${record.sandbox_type}`">
+ <div class="sandbox-card__badge">
+ <t-icon :name="typeIcon(record.sandbox_type)" size="18px" />
+ </div>
+ <div class="sandbox-card__body">
+ <div class="sandbox-card__header">
+ <h3 class="sandbox-card__title">{{ record.name }}</h3>
+ <div class="sandbox-card__actions" @click.stop>
+ <t-dropdown :options="cardMenu(record)" trigger="click" attach="body" placement="bottom-right"
+ @click="(data: any) => onMenuAction(data.value, record)">
+ <t-button variant="text" shape="square" size="small" class="sandbox-card__action-btn">
+ <t-icon name="ellipsis" />
+ </t-button>
+ </t-dropdown>
+ <t-tooltip :content="$t('common.delete')" placement="top">
+ <t-button theme="danger" shape="square" variant="text" size="small"
+ class="sandbox-card__action-btn" @click.stop="confirmDelete(record)">
+ <template #icon><t-icon name="delete" /></template>
+ </t-button>
+ </t-tooltip>
+ </div>
+ </div>
+ <p class="sandbox-card__subtitle">
+ <span>{{ backendLabel(record.sandbox_type) }}</span>
+ <t-tag v-if="isLegacyRecord(record)" theme="warning" variant="light" size="small" class="legacy-tag">
+ {{ $t('settings.sandbox.legacyConfig') }}
+ </t-tag>
+ <template v-if="endpointHost(record)">
+ <span class="sandbox-card__sep">·</span>
+ <span>{{ endpointHost(record) }}</span>
+ </template>
+ </p>
+ <p v-if="record.description" class="sandbox-card__desc">{{ record.description }}</p>
+ </div>
+ </div>
+ <button type="button" class="sandbox-card sandbox-card--add" @click="openCreate">
+ <span class="sandbox-card--add__icon" aria-hidden="true"><t-icon name="add" /></span>
+ <span class="sandbox-card--add__label">{{ $t('settings.sandbox.addConfig') }}</span>
+ </button>
+ </div>
+ <p v-if="!loading && records.length === 0" class="sandbox-empty-hint">
+ {{ $t('settings.sandbox.noConfigs') }}
+ </p>
+ </t-loading>
+
+ <SandboxConfigEditorDrawer v-model:visible="showEditor" :record="editingRecord"
+ :preset-type="activeType === 'all' ? '' : activeType" :defaults="defaults" @saved="load" />
+
+ <t-dialog v-model:visible="showDefaults" :header="$t('settings.sandbox.deployDefaultsTitle')" width="560px"
+ :cancel-btn="null" :confirm-btn="{ content: $t('common.close') }" @confirm="showDefaults = false">
+ <p class="dialog-hint">{{ $t('settings.sandbox.deployDefaultsHint') }}</p>
+ <ul class="defaults-list">
+ <li>
+ <span class="defaults-label">{{ $t('settings.sandbox.deployDefaultBackend') }}</span>
+ <span>{{ defaults?.sandbox_type ? backendLabel(defaults.sandbox_type) : '-' }}</span>
+ </li>
+ <template v-for="provider in defaultProviders" :key="provider.type">
+ <li class="defaults-group">{{ backendLabel(provider.type) }}</li>
+ <li v-for="row in provider.rows" :key="row.label">
+ <span class="defaults-label">{{ row.label }}</span>
+ <span>{{ row.value }}</span>
+ </li>
+ </template>
+ </ul>
+ </t-dialog>
+
+ <t-dialog v-model:visible="showInventory" :header="$t('settings.sandbox.inventoryTitle')" width="520px"
+ :cancel-btn="null" :confirm-btn="{ content: $t('common.close') }" @confirm="showInventory = false">
+ <t-loading :loading="inventoryLoading" size="small">
+ <div v-if="inventory" class="inventory">
+ <t-alert v-if="inventory.unverifiable" theme="warning"
+ :message="$t('settings.sandbox.inventoryUnverifiableHint')" />
+ <ul class="defaults-list">
+ <li>
+ <span class="defaults-label">{{ $t('settings.sandbox.sandboxCount') }}</span>
+ <span>{{ inventory.unverifiable
+ ? $t('settings.sandbox.sandboxCountUnknown')
+ : inventory.sandbox_count }}</span>
+ </li>
+ <li v-if="inventory.session_ids?.length">
+ <span class="defaults-label">{{ $t('settings.sandbox.affectedSessions', {
+ count: inventory.session_ids.length }) }}</span>
+ </li>
+ <li v-if="inventory.agent_names?.length">
+ <span class="defaults-label">{{ $t('settings.sandbox.affectedAgents', {
+ names: inventory.agent_names.join('、') }) }}</span>
+ </li>
+ </ul>
+ </div>
+ </t-loading>
+ </t-dialog>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, onMounted, ref } from 'vue'
+import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
+import SandboxConfigEditorDrawer from '@/components/SandboxConfigEditorDrawer.vue'
+import {
+ checkSandboxConfig,
+ deleteSandboxConfig,
+ getSandboxConfigInventory,
+ isNamedSandboxBackend,
+ listSandboxConfigs,
+ parseSandboxConflict,
+ setSandboxWorkspacePolicy,
+ type SandboxConfigDefaults,
+ type SandboxConfigRecord,
+ type SandboxInventory,
+} from '@/api/system'
+
+const { t } = useI18n()
+
+const backendTypes = ['cube', 'e2b'] as const
+
+const loading = ref(false)
+const policySaving = ref(false)
+const workspaceScriptsDisabled = ref(false)
+const records = ref<SandboxConfigRecord[]>([])
+const defaults = ref<SandboxConfigDefaults | null>(null)
+const activeType = ref<string>('all')
+
+const showEditor = ref(false)
+const editingRecord = ref<SandboxConfigRecord | null>(null)
+const showDefaults = ref(false)
+
+const showInventory = ref(false)
+const inventoryLoading = ref(false)
+const inventory = ref<SandboxInventory | null>(null)
+
+const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)
+
+const typeIcon = (type: string) => {
+ if (type === 'docker' || type === 'local') return 'server'
+ if (type === 'disabled') return 'minus-circle'
+ return 'cloud'
+}
+
+const isLegacyRecord = (record: SandboxConfigRecord) => !isNamedSandboxBackend(record.sandbox_type)
+
+const filteredRecords = computed(() => {
+ const base = activeType.value === 'all'
+ ? records.value
+ : records.value.filter((r) => r.sandbox_type === activeType.value)
+ return base
+})
+
+const countByType = (type: string) =>
+ records.value.filter((r) => r.sandbox_type === type && isNamedSandboxBackend(r.sandbox_type)).length
+
+const cardMenu = (record: SandboxConfigRecord) => {
+ if (isLegacyRecord(record)) {
+ return [{ content: t('common.delete'), value: 'delete-only' }]
+ }
+ return [
+ { content: t('common.edit'), value: 'edit' },
+ { content: t('settings.sandbox.testConnection'), value: 'check' },
+ { content: t('settings.sandbox.viewSandboxes'), value: 'inventory' },
+ ]
+}
+
+// The endpoint host is what tells two configs of the same backend apart at a
+// glance, which is the whole point of allowing several of them.
+function endpointHost(record: SandboxConfigRecord): string {
+ const raw = record.config?.e2b?.api_url || record.config?.cube?.api_url || ''
+ if (!raw) return ''
+ try {
+ return new URL(raw).host
+ } catch {
+ return raw
+ }
+}
+
+const defaultProviders = computed(() => {
+ const groups: { type: string; rows: { label: string; value: string }[] }[] = []
+ const describe = (type: 'cube' | 'e2b') => {
+ const provider = defaults.value?.[type]
+ if (!provider) return
+ const rows = [
+ { label: t('settings.sandbox.apiUrl'), value: provider.api_url || '-' },
+ ...(type === 'cube'
+ ? [{ label: t('settings.sandbox.proxyUrl'), value: provider.proxy_url || '-' }]
+ : []),
+ { label: t('settings.sandbox.sandboxDomain'), value: provider.sandbox_domain || '-' },
+ { label: t('settings.sandbox.templateId'), value: provider.template_id || '-' },
+ {
+ label: t('settings.sandbox.apiKey'),
+ value: provider.api_key_configured
+ ? t('settings.sandbox.apiKeyConfigured')
+ : t('settings.sandbox.apiKeyNotConfigured'),
+ },
+ ]
+ groups.push({ type, rows })
+ }
+ describe('cube')
+ describe('e2b')
+ return groups
+})
+
+// Agent references never block deletion, but the admin has to see which agents
+// will start failing — otherwise the breakage is discovered mid-conversation.
+// The inventory is fetched first purely for that warning; the DELETE itself is
+// still the authoritative check.
+async function confirmDelete(record: SandboxConfigRecord) {
+ let agents: string[] = []
+ try {
+ const res = await getSandboxConfigInventory(record.id)
+ agents = res?.data?.agent_names || []
+ } catch {
+ // An unreachable backend must not stop the admin from trying to delete.
+ }
+ const body = agents.length
+ ? t('settings.sandbox.confirmDeleteWithAgents', {
+ name: record.name,
+ agents: t('settings.sandbox.affectedAgents', { names: agents.join('、') }) + ' ',
+ })
+ : t('settings.sandbox.confirmDelete', { name: record.name })
+ const dialog = DialogPlugin.confirm({
+ header: t('common.confirmDelete'),
+ body,
+ theme: 'warning',
+ confirmBtn: { content: t('common.delete'), theme: 'danger' },
+ cancelBtn: t('common.cancel'),
+ onConfirm: async () => {
+ dialog.destroy()
+ await removeRecord(record)
+ },
+ })
+}
+
+function openCreate() {
+ editingRecord.value = null
+ showEditor.value = true
+}
+
+async function load() {
+ loading.value = true
+ try {
+ const res = await listSandboxConfigs()
+ records.value = res?.data || []
+ defaults.value = res?.defaults || null
+ workspaceScriptsDisabled.value = res?.workspace_scripts_disabled === true
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('settings.sandbox.loadFailed'))
+ } finally {
+ loading.value = false
+ }
+}
+
+function confirmDisableScripts() {
+ const dialog = DialogPlugin.confirm({
+ header: t('settings.sandbox.disableScripts'),
+ body: t('settings.sandbox.disableScriptsConfirm'),
+ theme: 'warning',
+ confirmBtn: { content: t('settings.sandbox.disableScripts'), theme: 'danger' },
+ cancelBtn: t('common.cancel'),
+ onConfirm: async () => {
+ dialog.destroy()
+ await setScriptsDisabled(true)
+ },
+ })
+}
+
+async function enableScripts() {
+ await setScriptsDisabled(false)
+}
+
+async function setScriptsDisabled(disabled: boolean) {
+ policySaving.value = true
+ try {
+ const res = await setSandboxWorkspacePolicy(disabled)
+ workspaceScriptsDisabled.value = res?.workspace_scripts_disabled === true
+ MessagePlugin.success(
+ disabled ? t('settings.sandbox.scriptsDisabled') : t('settings.sandbox.scriptsEnabled'),
+ )
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('settings.sandbox.policySaveFailed'))
+ } finally {
+ policySaving.value = false
+ }
+}
+
+async function onMenuAction(action: string, record: SandboxConfigRecord) {
+ if (action === 'delete-only') {
+ confirmDelete(record)
+ return
+ }
+ if (action === 'edit') {
+ editingRecord.value = record
+ showEditor.value = true
+ return
+ }
+ if (action === 'check') {
+ await runQuickCheck(record)
+ return
+ }
+ if (action === 'inventory') {
+ await openInventory(record)
+ }
+}
+
+// A card-level probe answers "is this backend still alive" without opening the
+// form; the per-probe breakdown and the sandbox-consuming deep check stay in the
+// editor, where the config being probed is on screen.
+async function runQuickCheck(record: SandboxConfigRecord) {
+ try {
+ const res = await checkSandboxConfig({ config_id: record.id })
+ const result = res?.data
+ if (result?.ok) {
+ MessagePlugin.success(t('settings.sandbox.checkPassed'))
+ return
+ }
+ const failed = result?.checks?.find((item) => item.ok === false)
+ MessagePlugin.error(failed?.message || t('settings.sandbox.checkFailed'))
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('settings.sandbox.checkFailed'))
+ }
+}
+
+async function openInventory(record: SandboxConfigRecord) {
+ showInventory.value = true
+ inventoryLoading.value = true
+ inventory.value = null
+ try {
+ const res = await getSandboxConfigInventory(record.id)
+ inventory.value = res?.data || null
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('settings.sandbox.inventoryFailed'))
+ showInventory.value = false
+ } finally {
+ inventoryLoading.value = false
+ }
+}
+
+async function removeRecord(record: SandboxConfigRecord, force = false) {
+ try {
+ await deleteSandboxConfig(record.id, force)
+ MessagePlugin.success(t('settings.sandbox.deleted'))
+ await load()
+ } catch (e: any) {
+ const refusal = parseSandboxConflict(e)
+ if (refusal?.code === 'sandboxes_still_live') {
+ // Counted sandboxes are never overridable: forcing the row away would
+ // leave paused instances nobody can reach, billing indefinitely.
+ showStillLiveDialog(refusal.inventory)
+ return
+ }
+ if (refusal?.code === 'sandbox_inventory_unverifiable') {
+ confirmForceDelete(record)
+ return
+ }
+ MessagePlugin.error(e?.message || t('settings.sandbox.deleteFailed'))
+ }
+}
+
+function showStillLiveDialog(inv?: SandboxInventory) {
+ const lines = [t('settings.sandbox.sandboxesStillLive', { count: inv?.sandbox_count ?? 0 })]
+ if (inv?.session_ids?.length) {
+ lines.push(t('settings.sandbox.affectedSessions', { count: inv.session_ids.length }))
+ }
+ lines.push(t('settings.sandbox.blockedHint'))
+ const dialog = DialogPlugin.alert({
+ header: t('settings.sandbox.inventoryTitle'),
+ // A dialog body is plain text, so newlines would collapse.
+ body: lines.join(' '),
+ confirmBtn: t('common.close'),
+ onConfirm: () => dialog.destroy(),
+ })
+}
+
+// Deleting is the one action with no second way out: an endpoint whose DNS
+// record is gone can never be verified again, so the row would be permanently
+// undeletable. The admin takes that call explicitly.
+function confirmForceDelete(record: SandboxConfigRecord) {
+ const dialog = DialogPlugin.confirm({
+ header: t('settings.sandbox.forceDeleteTitle'),
+ body: t('settings.sandbox.forceDeleteConfirm'),
+ theme: 'warning',
+ confirmBtn: { content: t('settings.sandbox.forceDelete'), theme: 'danger' },
+ cancelBtn: t('common.cancel'),
+ onConfirm: async () => {
+ dialog.destroy()
+ await removeRecord(record, true)
+ },
+ })
+}
+
+onMounted(load)
+</script>
+
+<style lang="less" scoped>
+.sandbox-settings {
+ padding: 4px 0;
+}
+
+.section-header h2 {
+ margin: 0 0 6px;
+ font-size: 18px;
+ font-weight: 600;
+}
+
+.section-description {
+ margin: 0 0 20px;
+ color: var(--td-text-color-secondary);
+ font-size: 13px;
+
+ &--hint {
+ margin-top: -12px;
+ margin-bottom: 20px;
+ }
+}
+
+.section-header__top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 20px;
+}
+
+.defaults-trigger {
+ --td-bg-color-container-hover: transparent;
+ flex-shrink: 0;
+ padding-left: 0;
+ padding-right: 0;
+ font-weight: 600;
+}
+
+.sandbox-list-loading {
+ min-height: 120px;
+}
+
+.sandbox-tabs-row {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
+ margin-bottom: 16px;
+}
+
+.sandbox-tabs-actions {
+ flex-shrink: 0;
+ padding-top: 4px;
+}
+
+.sandbox-type-tabs {
+ flex: 1;
+ min-width: 0;
+ margin-bottom: 0;
+
+ :deep(.t-tabs__nav-item) {
+ font-size: 13px;
+ }
+
+ :deep(.t-tabs__content) {
+ display: none;
+ }
+}
+
+.sandbox-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
+ gap: 12px;
+
+ .sandbox-card--add {
+ width: 100%;
+ height: 100%;
+ }
+}
+
+.sandbox-card {
+ position: relative;
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 14px 16px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 10px;
+ background: var(--td-bg-color-container);
+ transition: border-color 0.18s ease, box-shadow 0.18s ease;
+ min-width: 0;
+
+ &:hover {
+ border-color: var(--td-brand-color-3, var(--td-brand-color));
+ box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
+ }
+
+ &--add {
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 68px;
+ border-style: dashed;
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ font: inherit;
+ text-align: center;
+
+ &:hover,
+ &:focus-visible {
+ color: var(--td-brand-color);
+ border-color: var(--td-brand-color);
+ box-shadow: none;
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color);
+ outline-offset: 2px;
+ }
+
+ &__icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
+ color: var(--td-brand-color);
+ font-size: 18px;
+ }
+
+ &__label {
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 1.4;
+ }
+ }
+}
+
+.sandbox-card__badge {
+ flex-shrink: 0;
+ width: 36px;
+ height: 36px;
+ border-radius: 9px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin-top: 1px;
+ background: rgba(0, 82, 217, 0.1);
+ color: #0052D9;
+}
+
+.sandbox-card--e2b .sandbox-card__badge {
+ background: rgba(98, 53, 187, 0.1);
+ color: #6235BB;
+}
+
+.sandbox-card--docker .sandbox-card__badge,
+.sandbox-card--local .sandbox-card__badge {
+ background: rgba(17, 128, 83, 0.1);
+ color: #118053;
+}
+
+.sandbox-card__body {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: 2px;
+}
+
+.sandbox-card__header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+}
+
+.sandbox-card__title {
+ flex: 1;
+ min-width: 0;
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: var(--td-text-color-primary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.sandbox-card__subtitle,
+.sandbox-card__desc {
+ margin: 2px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-text-color-secondary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.sandbox-card__desc {
+ color: var(--td-text-color-placeholder);
+}
+
+.sandbox-card__sep {
+ margin: 0 4px;
+ color: var(--td-text-color-placeholder);
+}
+
+.legacy-tag {
+ margin-left: 6px;
+ vertical-align: middle;
+}
+
+.sandbox-card__actions {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.sandbox-card__action-btn {
+ flex-shrink: 0;
+ padding: 2px;
+ opacity: 0;
+ transition: opacity 0.15s ease;
+}
+
+.sandbox-card:hover .sandbox-card__action-btn,
+.sandbox-card:focus-within .sandbox-card__action-btn {
+ opacity: 1;
+}
+
+.sandbox-empty-hint {
+ margin: 16px 0 0;
+ font-size: 13px;
+ color: var(--td-text-color-placeholder);
+}
+
+.dialog-hint {
+ margin: 0 0 12px;
+ font-size: 13px;
+ color: var(--td-text-color-secondary);
+}
+
+.defaults-list {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 13px;
+}
+
+.defaults-group {
+ margin-top: 8px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+}
+
+.defaults-label {
+ display: inline-block;
+ min-width: 120px;
+ color: var(--td-text-color-secondary);
+}
+
+.inventory {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+</style>
diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue
index df87f00af..6f2d3b8f7 100644
--- a/frontend/src/views/settings/Settings.vue
+++ b/frontend/src/views/settings/Settings.vue
@@ -129,6 +129,11 @@
<StorageEngineSettings />
</div>
+ <!-- 沙箱后端 -->
+ <div v-if="currentSection === 'sandbox'" class="section">
+ <SandboxSettings />
+ </div>
+
<!-- 系统信息 -->
<div v-if="currentSection === 'system'" class="section">
<SystemInfo />
@@ -205,6 +210,7 @@ import ChatHistorySettings from './ChatHistorySettings.vue'
import VectorStoreSettings from './VectorStoreSettings.vue'
import ParserEngineSettings from './ParserEngineSettings.vue'
import StorageEngineSettings from './StorageBackendSettings.vue'
+import SandboxSettings from './SandboxSettings.vue'
import WeKnoraCloudSettings from './WeKnoraCloudSettings.vue'
import TenantMembers from './TenantMembers.vue'
import SystemSettings from '@/views/system/SystemSettings.vue'
@@ -329,6 +335,7 @@ const navItems = computed(() => {
{ key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') },
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
{ key: 'storage', icon: 'cloud', label: t('settings.storageEngine') },
+ { key: 'sandbox', icon: 'server', label: t('settings.sandbox.title') },
{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
{ key: 'system', icon: 'info-circle', label: t('settings.versionInfo') },
{ key: 'system-global', icon: 'server', label: t('settings.system') },
@@ -390,6 +397,7 @@ const navGroups = computed<NavGroup[]>(() => {
'vectorstore',
'parser',
'storage',
+ 'sandbox',
'websearch',
'mcp',
]),
diff --git a/go.mod b/go.mod
index 35593daa6..e5b7d221b 100644
--- a/go.mod
+++ b/go.mod
@@ -4,6 +4,7 @@ go 1.26.0
require (
codeberg.org/readeck/go-readability/v2 v2.1.2
+ connectrpc.com/connect v1.19.1
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.1
github.com/PuerkitoBio/goquery v1.12.0
@@ -35,6 +36,7 @@ require (
github.com/larksuite/oapi-sdk-go/v3 v3.9.7
github.com/longbridgeapp/opencc v0.3.13
github.com/mark3labs/mcp-go v0.52.0
+ github.com/matiasinsaurralde/go-e2b v0.1.1-0.20260808041540-fdc08ceaa1c1
github.com/milvus-io/milvus/client/v2 v2.6.4
github.com/minio/minio-go/v7 v7.1.0
github.com/mmcdole/gofeed v1.3.0
@@ -58,12 +60,13 @@ require (
github.com/swaggo/gin-swagger v1.6.1
github.com/swaggo/swag v1.16.6
github.com/tencent/vectordatabase-sdk-go v1.8.4
+ github.com/tencentcloud/CubeSandbox/sdk/go v0.0.0-20260807115140-5cefcca27a7f
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.103
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap v1.3.103
github.com/tencentyun/cos-go-sdk-v5 v0.7.73
github.com/tiktoken-go/tokenizer v0.7.0
- github.com/volcengine/vikingdb-go-sdk v0.0.11
github.com/volcengine/ve-tos-golang-sdk/v2 v2.9.4
+ github.com/volcengine/vikingdb-go-sdk v0.0.11
github.com/wailsapp/wails/v2 v2.12.0
github.com/weaviate/weaviate v1.37.3
github.com/weaviate/weaviate-go-client/v5 v5.7.3
diff --git a/go.sum b/go.sum
index e9e289427..c17f12be6 100644
--- a/go.sum
+++ b/go.sum
@@ -1326,6 +1326,8 @@ cloud.google.com/go/workflows v1.12.3/go.mod h1:fmOUeeqEwPzIU81foMjTRQIdwQHADi/v
cloud.google.com/go/workflows v1.12.4/go.mod h1:yQ7HUqOkdJK4duVtMeBCAOPiN1ZF1E9pAMX51vpwB/w=
codeberg.org/readeck/go-readability/v2 v2.1.2 h1:JBrdyYJBRPMBbodLM1b5KxCSDH+JqCkGcuVRD7ICBAw=
codeberg.org/readeck/go-readability/v2 v2.1.2/go.mod h1:Ut31sW4osSrJPR3T8eQslMh4+jbwimXqn0w0ReCT+PU=
+connectrpc.com/connect v1.19.1 h1:R5M57z05+90EfEvCY1b7hBxDVOUl45PrtXtAV2fOC14=
+connectrpc.com/connect v1.19.1/go.mod h1:tN20fjdGlewnSFeZxLKb0xwIZ6ozc3OQs2hTXy4du9w=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
entgo.io/ent v0.14.3 h1:wokAV/kIlH9TeklJWGGS7AYJdVckr0DloWjIcO9iIIQ=
entgo.io/ent v0.14.3/go.mod h1:aDPE/OziPEu8+OWbzy4UlvWmD2/kbRuWfK2A40hcxJM=
@@ -2239,6 +2241,8 @@ github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mark3labs/mcp-go v0.52.0 h1:uRSzupNSUyPGDpF4owY5X4zEpACPwBnlM3FAFuXN6gQ=
github.com/mark3labs/mcp-go v0.52.0/go.mod h1:Zg9cB2HdwdMMVgY0xtTzq3KvYIOJQDsaut+jWjwDaQY=
+github.com/matiasinsaurralde/go-e2b v0.1.1-0.20260808041540-fdc08ceaa1c1 h1:iEhD0FOnY0m/7SyTF3vijOXbO++uLNckvD2Ttp87vw0=
+github.com/matiasinsaurralde/go-e2b v0.1.1-0.20260808041540-fdc08ceaa1c1/go.mod h1:JTycrO2WcWcZeUNZH6XIk10sV7UixdsGKOt4HQXZiiQ=
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
@@ -2614,6 +2618,8 @@ github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
github.com/tencent/vectordatabase-sdk-go v1.8.4 h1:jVATTavFzDypX/TOx+eNrOJk7DcOA0U8REH5NEIC2bs=
github.com/tencent/vectordatabase-sdk-go v1.8.4/go.mod h1:cb53Vbd9Lnh3mA1CwqV9Jy8MrNsxpIUlrhzBiBE7A2M=
+github.com/tencentcloud/CubeSandbox/sdk/go v0.0.0-20260807115140-5cefcca27a7f h1:dHvDrWPIE2UPPo1yl8dv+LxBK7lyog3xWfWUlTaXtvI=
+github.com/tencentcloud/CubeSandbox/sdk/go v0.0.0-20260807115140-5cefcca27a7f/go.mod h1:4TpzAuDL+yundwIr7UK0N1hVV6L9R/sqcinE+z4W6G0=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.563/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.103 h1:W1dpZ/Q6+DjUpiAUSmIHuFn7rAvetlSqzQCtf0tKEEA=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.103/go.mod h1:r5r4xbfxSaeR04b166HGsBa/R4U3SueirEUpXGuw+Q0=
diff --git a/internal/agent/act.go b/internal/agent/act.go
index f8f25e690..6a7d4d19a 100644
--- a/internal/agent/act.go
+++ b/internal/agent/act.go
@@ -176,6 +176,9 @@ var toolDisplayNames = map[string]string{
agenttools.ToolWebFetch: "获取网页",
agenttools.ToolExecuteSkillScript: "执行技能脚本",
agenttools.ToolReadSkill: "读取技能",
+ agenttools.ToolListSandboxFiles: "列出沙箱文件",
+ agenttools.ToolReadSandboxFile: "读取沙箱文件",
+ agenttools.ToolShellExec: "执行沙箱命令",
}
// toolHintSensitiveArgs lists tools whose arguments should NOT be shown in hints
@@ -280,7 +283,7 @@ func (e *AgentEngine) executeToolCallsParallel(
Success: result.Success,
Duration: toolCall.Duration,
Iteration: iteration,
- Data: result.Data,
+ Data: agenttools.SanitizeToolDataForPersist(toolCall.Name, result.Data),
},
})
@@ -326,7 +329,7 @@ func (e *AgentEngine) executeSingleToolCall(
Success: result.Success,
Duration: toolCall.Duration,
Iteration: iteration,
- Data: result.Data,
+ Data: agenttools.SanitizeToolDataForPersist(toolCall.Name, result.Data),
},
})
@@ -455,16 +458,17 @@ func (e *AgentEngine) runToolCall(
})
principal, _ := types.PrincipalFromContext(ctx)
+ execTimeout := toolExecutionTimeout(tc.Function.Name)
toolExecCtx := agenttools.WithToolExecContext(toolCtx, &agenttools.ToolExecContext{
SessionID: sessionID,
AssistantMessageID: assistantMessageID,
EventBus: e.eventBus,
ToolCallID: tc.ID,
UserID: principal.StorageID(),
- // ApprovalCtx keeps the round-level ctx without the per-tool 60s timeout,
+ // ApprovalCtx keeps the round-level ctx without the per-tool execution timeout,
// so MCP tool human-approval (issue #1173) can legitimately block longer.
ApprovalCtx: toolCtx,
- ExecTimeout: defaultToolExecTimeout,
+ ExecTimeout: execTimeout,
})
var result *types.ToolResult
@@ -475,7 +479,7 @@ func (e *AgentEngine) runToolCall(
// never reach persistence, an external service, or a routing decision.
err = fmt.Errorf("tool arguments contain unresolved model handles: %v", tc.UnresolvedHandles)
} else {
- execCtx, toolCancel := context.WithTimeout(toolExecCtx, defaultToolExecTimeout)
+ execCtx, toolCancel := context.WithTimeout(toolExecCtx, execTimeout)
result, err = e.toolRegistry.ExecuteTool(
execCtx, tc.Function.Name,
json.RawMessage(tc.Function.Arguments),
diff --git a/internal/agent/const.go b/internal/agent/const.go
index 297ad0dbb..b865131c2 100644
--- a/internal/agent/const.go
+++ b/internal/agent/const.go
@@ -24,6 +24,10 @@ const (
// defaultToolExecTimeout is the default maximum time for a single tool execution.
// Prevents long-running tools (web_fetch, database_query) from hanging indefinitely.
defaultToolExecTimeout = 60 * time.Second
+ // shellExecToolTimeout is slightly longer than shell_exec's own hard
+ // 600-second command timeout so the tool can return a structured timeout
+ // result instead of being cancelled first by the generic agent wrapper.
+ shellExecToolTimeout = 10*time.Minute + 5*time.Second
// maxLLMRetries is the maximum number of retries for transient LLM errors.
maxLLMRetries = 2
@@ -42,6 +46,13 @@ const (
maxRepeatedResponseRounds = 2
)
+func toolExecutionTimeout(toolName string) time.Duration {
+ if toolName == "shell_exec" {
+ return shellExecToolTimeout
+ }
+ return defaultToolExecTimeout
+}
+
// transientErrorMarkers are substrings that indicate a transient (retryable) error.
var transientErrorMarkers = []string{
"429", "rate limit",
diff --git a/internal/agent/const_test.go b/internal/agent/const_test.go
new file mode 100644
index 000000000..b347cde76
--- /dev/null
+++ b/internal/agent/const_test.go
@@ -0,0 +1,13 @@
+package agent
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestToolExecutionTimeout(t *testing.T) {
+ assert.Equal(t, 10*time.Minute+5*time.Second, toolExecutionTimeout("shell_exec"))
+ assert.Equal(t, 60*time.Second, toolExecutionTimeout("web_fetch"))
+}
diff --git a/internal/agent/engine.go b/internal/agent/engine.go
index 56188daa1..ca9b7944a 100644
--- a/internal/agent/engine.go
+++ b/internal/agent/engine.go
@@ -112,6 +112,10 @@ func (e *AgentEngine) systemPromptOptions(ctx context.Context) *BuildSystemPromp
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
opts.SkillsMetadata = e.skillsManager.GetAllMetadata()
}
+ if e.toolRegistry != nil {
+ _, err := e.toolRegistry.GetTool(agenttools.ToolShellExec)
+ opts.ShellExecEnabled = err == nil
+ }
return opts
}
diff --git a/internal/agent/observe.go b/internal/agent/observe.go
index 45e599d88..da829f121 100644
--- a/internal/agent/observe.go
+++ b/internal/agent/observe.go
@@ -17,10 +17,22 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
+const (
+ minCurrentTurnToolTokens = 8 * 1024
+ maxCurrentTurnToolTokens = 32 * 1024
+ currentTurnToolTokenFraction = 5 // 20%
+)
+
// manageContextWindow consolidates or compresses messages if approaching the token limit.
// currentTokens is the caller's best estimate of the current context size (using
// API-reported Usage when available, falling back to BPE estimation).
func (e *AgentEngine) manageContextWindow(ctx context.Context, messages []chat.Message, round, currentTokens int) []chat.Message {
+ var trimmed bool
+ messages, trimmed = trimCurrentTurnToolResults(messages, e.tokenEstimator, currentTurnToolResultBudget(e.config.MaxContextTokens))
+ if trimmed {
+ currentTokens = e.tokenEstimator.EstimateMessages(messages)
+ logger.Infof(ctx, "[Agent][Round-%d] Trimmed current-turn tool results to token budget", round)
+ }
if e.config.MaxContextTokens <= 0 {
return messages
}
@@ -50,6 +62,124 @@ func (e *AgentEngine) manageContextWindow(ctx context.Context, messages []chat.M
return messages
}
+func currentTurnToolResultBudget(maxContextTokens int) int {
+ if maxContextTokens <= 0 {
+ return maxCurrentTurnToolTokens
+ }
+ budget := maxContextTokens / currentTurnToolTokenFraction
+ if budget < minCurrentTurnToolTokens {
+ return minCurrentTurnToolTokens
+ }
+ if budget > maxCurrentTurnToolTokens {
+ return maxCurrentTurnToolTokens
+ }
+ return budget
+}
+
+// trimCurrentTurnToolResults returns a message copy for the next model call.
+// It never mutates ToolResult objects used by SSE, diagnostics, or persistence.
+// Assistant tool-call messages remain untouched so every compacted tool result
+// retains its provider-required call/result pairing.
+func trimCurrentTurnToolResults(
+ messages []chat.Message,
+ estimator *agenttoken.Estimator,
+ budget int,
+) ([]chat.Message, bool) {
+ if estimator == nil || budget <= 0 || len(messages) == 0 {
+ return messages, false
+ }
+
+ lastUser := -1
+ for i := len(messages) - 1; i >= 0; i-- {
+ if messages[i].Role == "user" {
+ lastUser = i
+ break
+ }
+ }
+ if lastUser < 0 {
+ return messages, false
+ }
+
+ var toolIndexes []int
+ total := 0
+ for i := lastUser + 1; i < len(messages); i++ {
+ if messages[i].Role == "tool" {
+ toolIndexes = append(toolIndexes, i)
+ total += estimator.EstimateMessage(&messages[i])
+ }
+ }
+ if total <= budget || len(toolIndexes) == 0 {
+ return messages, false
+ }
+
+ out := append([]chat.Message(nil), messages...)
+ baseCosts := make(map[int]int, len(toolIndexes))
+ remaining := budget
+ for _, idx := range toolIndexes {
+ out[idx].Content = compactedToolResultMarker(messages[idx].Content)
+ cost := estimator.EstimateMessage(&out[idx])
+ baseCosts[idx] = cost
+ remaining -= cost
+ }
+ if remaining < 0 {
+ remaining = 0
+ }
+
+ // Spend the remaining budget newest-first. A result that cannot fit in
+ // full receives the largest head/tail preview that does fit.
+ for i := len(toolIndexes) - 1; i >= 0; i-- {
+ idx := toolIndexes[i]
+ fullCost := estimator.EstimateMessage(&messages[idx])
+ extra := fullCost - baseCosts[idx]
+ if extra <= remaining {
+ out[idx] = messages[idx]
+ remaining -= extra
+ continue
+ }
+ out[idx] = compactToolMessage(messages[idx], baseCosts[idx]+remaining, estimator)
+ remaining = 0
+ }
+ return out, true
+}
+
+func compactedToolResultMarker(content string) string {
+ return fmt.Sprintf(
+ "[Tool result compacted: original_bytes=%d. Re-run the tool with narrower filters or a smaller range if more detail is needed.]",
+ len(content),
+ )
+}
+
+func compactToolMessage(msg chat.Message, maxTokens int, estimator *agenttoken.Estimator) chat.Message {
+ runes := []rune(msg.Content)
+ base := msg
+ base.Content = compactedToolResultMarker(msg.Content)
+ if len(runes) == 0 || estimator.EstimateMessage(&base) >= maxTokens {
+ return base
+ }
+
+ best := base
+ low, high := 1, len(runes)
+ for low <= high {
+ keep := low + (high-low)/2
+ head := keep / 4
+ tail := keep - head
+ candidate := base
+ candidate.Content = fmt.Sprintf(
+ "%s\n\n%s\n...[tool result preview omitted]...\n%s",
+ base.Content,
+ string(runes[:head]),
+ string(runes[len(runes)-tail:]),
+ )
+ if estimator.EstimateMessage(&candidate) <= maxTokens {
+ best = candidate
+ low = keep + 1
+ } else {
+ high = keep - 1
+ }
+ }
+ return best
+}
+
// responseVerdict captures the result of analyzing an LLM response to determine
// whether the agent loop should stop and what the final answer is (if any).
type responseVerdict struct {
diff --git a/internal/agent/observe_test.go b/internal/agent/observe_test.go
index 2ceb2cab0..405e64f79 100644
--- a/internal/agent/observe_test.go
+++ b/internal/agent/observe_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"time"
+ agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/modelcontext"
"github.com/Tencent/WeKnora/internal/models/chat"
@@ -15,6 +16,58 @@ import (
"github.com/stretchr/testify/require"
)
+func TestCurrentTurnToolResultBudgetBounds(t *testing.T) {
+ assert.Equal(t, maxCurrentTurnToolTokens, currentTurnToolResultBudget(0))
+ assert.Equal(t, minCurrentTurnToolTokens, currentTurnToolResultBudget(10_000))
+ assert.Equal(t, 20_000, currentTurnToolResultBudget(100_000))
+ assert.Equal(t, maxCurrentTurnToolTokens, currentTurnToolResultBudget(1_000_000))
+}
+
+func TestTrimCurrentTurnToolResultsKeepsNewestAndPairing(t *testing.T) {
+ estimator, err := agenttoken.NewEstimator()
+ require.NoError(t, err)
+
+ messages := []chat.Message{
+ {Role: "user", Content: "old turn"},
+ {Role: "tool", Name: "old", ToolCallID: "old-call", Content: strings.Repeat("historical ", 1000)},
+ {Role: "assistant", Content: "old answer"},
+ {Role: "user", Content: "current turn"},
+ {
+ Role: "assistant",
+ ToolCalls: []chat.ToolCall{
+ {ID: "call-1", Type: "function"},
+ {ID: "call-2", Type: "function"},
+ {ID: "call-3", Type: "function"},
+ },
+ },
+ {Role: "tool", Name: "one", ToolCallID: "call-1", Content: strings.Repeat("alpha beta gamma ", 1000)},
+ {Role: "tool", Name: "two", ToolCallID: "call-2", Content: strings.Repeat("delta epsilon zeta ", 1000)},
+ {Role: "tool", Name: "three", ToolCallID: "call-3", Content: strings.Repeat("newest result ", 100)},
+ }
+ latestCost := estimator.EstimateMessage(&messages[7])
+ markerOne := messages[5]
+ markerOne.Content = compactedToolResultMarker(markerOne.Content)
+ markerTwo := messages[6]
+ markerTwo.Content = compactedToolResultMarker(markerTwo.Content)
+ budget := latestCost + estimator.EstimateMessage(&markerOne) + estimator.EstimateMessage(&markerTwo)
+
+ trimmed, changed := trimCurrentTurnToolResults(messages, estimator, budget)
+
+ require.True(t, changed)
+ assert.Equal(t, messages[1].Content, trimmed[1].Content, "historical results are handled separately")
+ assert.Contains(t, trimmed[5].Content, "Tool result compacted")
+ assert.Contains(t, trimmed[6].Content, "Tool result compacted")
+ assert.Equal(t, messages[7].Content, trimmed[7].Content, "newest result should be kept in full")
+ assert.Equal(t, messages[4].ToolCalls, trimmed[4].ToolCalls, "assistant tool-call pairing must remain intact")
+ assert.Equal(t, strings.Repeat("alpha beta gamma ", 1000), messages[5].Content, "input messages must not be mutated")
+
+ total := 0
+ for _, idx := range []int{5, 6, 7} {
+ total += estimator.EstimateMessage(&trimmed[idx])
+ }
+ assert.LessOrEqual(t, total, budget)
+}
+
// TestAnalyzeResponse_ToolCall_DoesNotTerminate is a regression guard: the
// agent has no dedicated terminal tool — any round that requests tool calls is
// non-terminal and must keep the loop running. The agent ends only by stopping
diff --git a/internal/agent/prompts.go b/internal/agent/prompts.go
index a6b571a8c..01575b336 100644
--- a/internal/agent/prompts.go
+++ b/internal/agent/prompts.go
@@ -229,7 +229,7 @@ func renderPromptPlaceholders(template string, knowledgeBases []*KnowledgeBaseIn
// formatSkillsMetadata formats skills metadata for the system prompt (Level 1 - Progressive Disclosure)
// This is a lightweight representation that only includes skill name and description
-func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
+func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata, shellExecEnabled bool) string {
if len(skillsMetadata) == 0 {
return ""
}
@@ -257,7 +257,18 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
builder.WriteString("- `read_skill(skill_name)`: Load full skill instructions (MUST call before using a skill)\n")
builder.WriteString("- `execute_skill_script(skill_name, script_path, args, input)`: Run utility scripts bundled with a skill\n")
builder.WriteString(" - `input`: Pass data directly via stdin (use this when you have data in memory, e.g. JSON string)\n")
- builder.WriteString(" - `args`: Command-line arguments (only use `--file` if you have an actual file path in the skill directory)\n")
+ builder.WriteString(" - `args`: Command-line arguments; pass absolute `/workspace/input/...` paths from `<sandbox_attachments>` for user-uploaded files\n")
+ builder.WriteString(" - Treat `/workspace/input` as read-only and write generated files only to `$WEKNORA_SKILL_OUTPUT_DIR`\n")
+ if shellExecEnabled {
+ builder.WriteString("- `shell_exec(command, work_dir, timeout_sec, max_output_bytes, max_stderr_bytes, env)`: Freely execute shell commands and explore the current session's isolated Cube sandbox\n")
+ builder.WriteString(" - User-uploaded files are restored under `/workspace/input` and listed in `<sandbox_attachments>`\n")
+ builder.WriteString(" - Use `find` and `file` to discover files and types; use `cat`, `head`, `tail`, and `sed` to inspect text; use `grep` and `awk` to search and process content\n")
+ builder.WriteString(" - Use shell pipelines, redirects, scripts, package managers, compilers, and other installed commands whenever they are the most direct way to complete the task\n")
+ builder.WriteString(" - Increase `max_output_bytes` up to 65536 per stream for large text output, or use `sed`/`head`/`tail` for targeted sections\n")
+ builder.WriteString(" - Binary output is suppressed; write binary results under `/workspace/output` so ArtifactCollector attaches them for download\n")
+ builder.WriteString(" - Session state persists across later `shell_exec` and `execute_skill_script` calls\n")
+ builder.WriteString(" - Non-zero exit codes are normal results, not tool errors — inspect stderr and decide what to do next\n")
+ }
return builder.String()
}
@@ -295,9 +306,10 @@ func renderPromptPlaceholdersWithStatus(
// BuildSystemPromptOptions contains optional parameters for BuildSystemPrompt
type BuildSystemPromptOptions struct {
- SkillsMetadata []*skills.SkillMetadata
- Language string // User language name for {{language}} placeholder (e.g. "Chinese (Simplified)")
- Config *config.Config // Config for reading prompt templates; nil falls back to hardcoded defaults
+ SkillsMetadata []*skills.SkillMetadata
+ ShellExecEnabled bool
+ Language string // User language name for {{language}} placeholder (e.g. "Chinese (Simplified)")
+ Config *config.Config // Config for reading prompt templates; nil falls back to hardcoded defaults
}
// BuildSystemPrompt builds the progressive RAG system prompt
@@ -346,7 +358,7 @@ func BuildSystemPromptWithOptions(
// Append skills metadata if available (Level 1 - Progressive Disclosure)
if options != nil && len(options.SkillsMetadata) > 0 {
- basePrompt += formatSkillsMetadata(options.SkillsMetadata)
+ basePrompt += formatSkillsMetadata(options.SkillsMetadata, options.ShellExecEnabled)
}
return basePrompt
diff --git a/internal/agent/prompts_shell_test.go b/internal/agent/prompts_shell_test.go
new file mode 100644
index 000000000..39b45df6d
--- /dev/null
+++ b/internal/agent/prompts_shell_test.go
@@ -0,0 +1,24 @@
+package agent
+
+import (
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/agent/skills"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFormatSkillsMetadataIncludesShellGuidanceOnlyWhenEnabled(t *testing.T) {
+ metadata := []*skills.SkillMetadata{{Name: "demo", Description: "demo skill"}}
+
+ enabled := formatSkillsMetadata(metadata, true)
+ require.Contains(t, enabled, "shell_exec")
+ for _, command := range []string{"find", "file", "cat", "head", "tail", "sed", "grep", "awk"} {
+ assert.Contains(t, enabled, command)
+ }
+ assert.Contains(t, enabled, "Freely execute shell commands")
+ assert.Contains(t, enabled, "Binary output is suppressed")
+
+ disabled := formatSkillsMetadata(metadata, false)
+ assert.NotContains(t, disabled, "shell_exec")
+}
diff --git a/internal/agent/skills/manager.go b/internal/agent/skills/manager.go
index 1557bc521..6305ebaf2 100644
--- a/internal/agent/skills/manager.go
+++ b/internal/agent/skills/manager.go
@@ -3,11 +3,67 @@ package skills
import (
"context"
"fmt"
+ "os"
+ "path"
+ "strings"
"sync"
+ "github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
)
+// artifactOutputEnvVar is the name of the environment variable that WeKnora
+// injects into every skill script execution. The value points to the
+// convention-driven directory where the script should drop artifacts the user
+// will be able to download after the turn completes.
+//
+// The name is stable across releases; skills reference it via os.getenv(...)
+// so they never hard-code the path.
+const artifactOutputEnvVar = "WEKNORA_SKILL_OUTPUT_DIR"
+
+// sessionInputEnvVar points skill scripts at user-uploaded files restored into
+// the current session's Cube. Inputs are separate from generated artifacts.
+const sessionInputEnvVar = "WEKNORA_SESSION_INPUT_DIR"
+
+// artifactHistoryEnvVar is the name of the environment variable that points
+// to the root artifact output directory (/workspace/output). Skill scripts
+// can use this to self-discover artifacts from prior runs when they need to
+// chain without LLM mediation.
+const artifactHistoryEnvVar = "WEKNORA_SKILL_HISTORY_ROOT"
+
+// defaultArtifactOutputDir is used when neither the environment variable
+// (WEKNORA_SKILL_OUTPUT_DIR) nor the ExecuteConfig.Env has an override.
+// /workspace/output sits inside the base sandbox image's writable tree and
+// is guaranteed to survive across Execute calls for the same session (Cube
+// SessionBoundManager keeps the MicroVM alive between calls).
+const defaultArtifactOutputDir = "/workspace/output"
+
+// ArtifactOutputDir returns the absolute path (inside the sandbox) where
+// skill scripts should write artifacts for this turn. It is exported so
+// callers such as ArtifactCollector can list the same directory when
+// draining artifacts after Execute returns.
+//
+// Resolution order (first non-empty wins):
+// 1. WEKNORA_SKILL_OUTPUT_DIR from the host environment (ops override).
+// 2. defaultArtifactOutputDir.
+//
+// Callers are expected to treat the returned string as read-only: the path
+// is normalised (no trailing slash) so it can be joined safely.
+func ArtifactOutputDir() string {
+ if v := strings.TrimSpace(os.Getenv(artifactOutputEnvVar)); v != "" {
+ return path.Clean(v)
+ }
+ return defaultArtifactOutputDir
+}
+
+// SkillOutputDir returns the artifact output directory for skill executions.
+// All skills write to the same root directory (/workspace/output/) to enable
+// collaboration and file sharing between different skill executions.
+func (m *Manager) SkillOutputDir(sessionID, skillName string) string {
+ return ArtifactOutputDir()
+}
+
// Manager manages skills lifecycle including discovery, loading, and script execution
// It coordinates between the Loader (filesystem operations) and Sandbox (script execution)
type Manager struct {
@@ -203,17 +259,58 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin
}
// Prepare execution config
+ logger.Info(ctx, "[Tool][ExecuteScript]:Prepare execution config")
+ sessionID, _ := types.SessionIDFromContext(ctx)
+
+ // Compute the artifact output directory. All skills share the same root
+ // directory (/workspace/output/) to enable collaboration and file sharing
+ // between different skill executions in the same session.
+ // Skill scripts read the directory via WEKNORA_SKILL_OUTPUT_DIR; the
+ // root (for cross-run discovery) is available via WEKNORA_SKILL_HISTORY_ROOT.
+ outputDir := m.SkillOutputDir(sessionID, skillName)
+ env := map[string]string{
+ artifactOutputEnvVar: outputDir,
+ artifactHistoryEnvVar: ArtifactOutputDir(),
+ }
+ // SessionFileStore advertises the "sandbox provides per-session file
+ // storage" capability. When present we can safely expose the input
+ // staging directory and pre-materialise the output directory; when
+ // absent (Local/Docker or fallback), stateless backends materialise
+ // directories on their own during script execution.
+ fileStore := sessionFileStoreFromManager(m.sandboxMgr)
+ if fileStore != nil {
+ env[sessionInputEnvVar] = sandbox.SessionInputRoot
+ if sessionID != "" {
+ if err := fileStore.EnsureSessionDir(ctx, sessionID, outputDir); err != nil {
+ logger.Warnf(ctx, "[Tool][ExecuteScript] pre-create output dir %s failed: %v", outputDir, err)
+ }
+ }
+ }
+
config := &sandbox.ExecuteConfig{
- Script: file.Path,
- Args: args,
- WorkDir: basePath,
- Stdin: stdin,
+ Script: file.Path,
+ Args: args,
+ WorkDir: basePath,
+ Stdin: stdin,
+ Env: env,
+ SessionID: sessionID,
}
// Execute in sandbox
return m.sandboxMgr.Execute(ctx, config)
}
+// sessionFileStoreFromManager returns the sandbox manager's effective
+// session filesystem capability, or nil when the backend cannot expose one.
+// Isolated in a helper so callers stay free of provider-specific branches.
+func sessionFileStoreFromManager(mgr sandbox.Manager) sandbox.SessionFileStore {
+ provider, ok := mgr.(sandbox.SessionCapabilityProvider)
+ if !ok || provider == nil {
+ return nil
+ }
+ return provider.SessionFileStore()
+}
+
// GetSkillInfo returns detailed information about a skill
func (m *Manager) GetSkillInfo(ctx context.Context, skillName string) (*SkillInfo, error) {
if !m.enabled {
diff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.go
index 4bad50b25..0139d9841 100644
--- a/internal/agent/tools/definitions.go
+++ b/internal/agent/tools/definitions.go
@@ -21,6 +21,19 @@ const (
// Skills-related tools (only available when skills are enabled)
ToolExecuteSkillScript = "execute_skill_script"
ToolReadSkill = "read_skill"
+ // Sandbox filesystem inspection (read-only; only available when the
+ // sandbox backend supports per-session file listing — currently the
+ // Cube SessionBoundManager). Lets the LLM discover and inspect files
+ // produced by prior skill executions in the same session so chained
+ // skills stop guessing paths.
+ 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.
+ ToolShellExec = "shell_exec"
// Wiki-related tools (only available when wiki KBs are in scope)
ToolWikiReadPage = "wiki_read_page"
ToolWikiWritePage = "wiki_write_page"
@@ -57,6 +70,9 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
+ {Name: ToolListSandboxFiles, Label: "列出沙箱文件", Description: "列出当前会话沙箱产出目录下的文件"},
+ {Name: ToolReadSandboxFile, Label: "读取沙箱文件", Description: "读取当前会话沙箱中已生成的文件内容"},
+ {Name: ToolShellExec, Label: "执行沙箱命令", Description: "在当前会话沙箱中执行 shell 命令(如安装依赖、检查环境)"},
{Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},
{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
{Name: ToolWikiReadSourceDoc, Label: "精读源文档", Description: "使用知识点深入阅读特定原始文档"},
diff --git a/internal/agent/tools/persist.go b/internal/agent/tools/persist.go
index ba38641ad..5a6aec4f0 100644
--- a/internal/agent/tools/persist.go
+++ b/internal/agent/tools/persist.go
@@ -13,6 +13,13 @@ var persistStripFields = map[string][]string{
"grep_results": {"chunk_results"},
}
+var persistStripFieldsByTool = map[string][]string{
+ ToolShellExec: {"stdout", "stderr", "content", "content_base64"},
+ ToolReadSandboxFile: {"stdout", "stderr", "content", "content_base64"},
+}
+
+const historicalSandboxOutputChars = 4 * 1024
+
// ShouldOmitRawToolOutput reports whether the raw XML/text Output should be
// excluded from SSE replay and persisted agent_steps. The full Output remains
// available in-memory for the current agent turn.
@@ -25,7 +32,7 @@ func ShouldOmitRawToolOutput(_ string, data map[string]interface{}) bool {
}
// SanitizeToolDataForPersist returns a copy of tool Data safe for DB / SSE replay.
-func SanitizeToolDataForPersist(data map[string]interface{}) map[string]interface{} {
+func SanitizeToolDataForPersist(toolName string, data map[string]interface{}) map[string]interface{} {
if data == nil {
return nil
}
@@ -37,17 +44,20 @@ func SanitizeToolDataForPersist(data map[string]interface{}) map[string]interfac
for _, key := range persistStripFields[displayType] {
delete(out, key)
}
+ for _, key := range persistStripFieldsByTool[toolName] {
+ delete(out, key)
+ }
return out
}
// SanitizeToolResultForClient builds stream / persistence metadata for the UI.
-func SanitizeToolResultForClient(_ string, result *types.ToolResult) map[string]interface{} {
+func SanitizeToolResultForClient(toolName string, result *types.ToolResult) map[string]interface{} {
meta := map[string]interface{}{}
if result == nil {
return meta
}
if result.Data != nil {
- for k, v := range SanitizeToolDataForPersist(result.Data) {
+ for k, v := range SanitizeToolDataForPersist(toolName, result.Data) {
meta[k] = v
}
}
@@ -88,8 +98,10 @@ func SanitizeAgentStepsForStorage(steps []types.AgentStep) []types.AgentStep {
result := *tc.Result
if ShouldOmitRawToolOutput(tc.Name, result.Data) {
result.Output = compactToolSummary(result.Success, result.Error, result.Data)
- result.Data = SanitizeToolDataForPersist(result.Data)
+ } else if isSandboxContentTool(tc.Name) {
+ result.Output = compactHistoricalSandboxOutput(result.Output)
}
+ result.Data = SanitizeToolDataForPersist(tc.Name, result.Data)
toolCalls[j].Result = &result
}
out[i].ToolCalls = toolCalls
@@ -109,11 +121,29 @@ func CompactToolOutputForHistory(toolName string, result *types.ToolResult) stri
return "Error: tool call failed"
}
if result.Output != "" && !ShouldOmitRawToolOutput(toolName, result.Data) {
+ if isSandboxContentTool(toolName) {
+ return compactHistoricalSandboxOutput(result.Output)
+ }
return result.Output
}
return compactToolSummary(result.Success, result.Error, result.Data)
}
+func isSandboxContentTool(toolName string) bool {
+ return toolName == ToolShellExec || toolName == ToolReadSandboxFile
+}
+
+func compactHistoricalSandboxOutput(output string) string {
+ if len(output) <= historicalSandboxOutputChars {
+ return output
+ }
+ const marker = "\n...[historical tool output compacted]...\n"
+ kept := historicalSandboxOutputChars - len(marker)
+ head := kept / 4
+ tail := kept - head
+ return output[:head] + marker + output[len(output)-tail:]
+}
+
func compactToolSummary(success bool, errMsg string, data map[string]interface{}) string {
if !success {
if errMsg != "" {
diff --git a/internal/agent/tools/persist_test.go b/internal/agent/tools/persist_test.go
index dd4b7ba66..f16ebf003 100644
--- a/internal/agent/tools/persist_test.go
+++ b/internal/agent/tools/persist_test.go
@@ -27,7 +27,7 @@ func TestSanitizeToolDataForPersist_knowledgeChunksList(t *testing.T) {
"total_chunks": 282,
"chunks": []map[string]interface{}{{"content": "secret"}},
}
- out := SanitizeToolDataForPersist(data)
+ out := SanitizeToolDataForPersist(ToolListKnowledgeChunks, data)
if _, ok := out["chunks"]; ok {
t.Fatal("chunk bodies should be stripped from persisted tool data")
}
@@ -87,3 +87,43 @@ func TestSanitizeToolResultForClient_omitsOutput(t *testing.T) {
t.Fatalf("summary metadata should remain, got %#v", meta["fetched_chunks"])
}
}
+
+func TestSandboxToolPersistenceStripsDuplicatePayloadsAndCompactsHistory(t *testing.T) {
+ rawOutput := strings.Repeat("shell output ", 1000)
+ steps := []types.AgentStep{{
+ ToolCalls: []types.ToolCall{{
+ Name: ToolShellExec,
+ Result: &types.ToolResult{
+ Success: true,
+ Output: rawOutput,
+ Data: map[string]interface{}{
+ "stdout": strings.Repeat("x", 10000),
+ "stderr": strings.Repeat("y", 10000),
+ "content": strings.Repeat("z", 10000),
+ "content_base64": strings.Repeat("A", 10000),
+ "exit_code": 0,
+ "stdout_original_bytes": 10000,
+ "stdout_truncated": true,
+ },
+ },
+ }},
+ }}
+
+ sanitized := SanitizeAgentStepsForStorage(steps)
+ result := sanitized[0].ToolCalls[0].Result
+
+ assert := func(condition bool, message string) {
+ t.Helper()
+ if !condition {
+ t.Fatal(message)
+ }
+ }
+ assert(len(result.Output) <= historicalSandboxOutputChars, "persisted shell output must be capped")
+ for _, key := range []string{"stdout", "stderr", "content", "content_base64"} {
+ _, exists := result.Data[key]
+ assert(!exists, key+" should be stripped")
+ }
+ assert(result.Data["exit_code"] == 0, "exit metadata should remain")
+ assert(len(CompactToolOutputForHistory(ToolShellExec, steps[0].ToolCalls[0].Result)) <= historicalSandboxOutputChars,
+ "historical replay must independently cap legacy raw output")
+}
diff --git a/internal/agent/tools/registry.go b/internal/agent/tools/registry.go
index 53b701477..c6a41fa79 100644
--- a/internal/agent/tools/registry.go
+++ b/internal/agent/tools/registry.go
@@ -21,6 +21,13 @@ type ToolRegistry struct {
maxToolOutputSize int // maximum chars for tool output (0 = use DefaultMaxToolOutput)
}
+// outputLimitProvider is implemented by tools that expose a caller-configurable
+// output budget with their own hard safety cap. It prevents the registry's
+// generic limit from undoing that explicit bounded choice.
+type outputLimitProvider interface {
+ OutputLimitChars(args json.RawMessage) int
+}
+
// NewToolRegistry creates a new tool registry
func NewToolRegistry() *ToolRegistry {
return &ToolRegistry{
@@ -144,6 +151,11 @@ func (r *ToolRegistry) ExecuteTool(
// Publish the ceiling so budget-aware tools can shape a batched result
// themselves; the truncation below stays as the fallback for the rest.
maxOutput := r.getMaxToolOutput()
+ if provider, ok := tool.(outputLimitProvider); ok {
+ if toolLimit := provider.OutputLimitChars(args); toolLimit > maxOutput {
+ maxOutput = toolLimit
+ }
+ }
result, execErr := tool.Execute(WithOutputBudget(ctx, maxOutput), args)
// Truncate large tool outputs to prevent context window poisoning. The
diff --git a/internal/agent/tools/sandbox_ls.go b/internal/agent/tools/sandbox_ls.go
new file mode 100644
index 000000000..fb19b4cb3
--- /dev/null
+++ b/internal/agent/tools/sandbox_ls.go
@@ -0,0 +1,298 @@
+// Package tools — list_sandbox_files.
+//
+// Read-only tool that lets the LLM enumerate files under a session's
+// sandbox artifact output directory. Without this tool, the LLM cannot
+// see files produced by prior skill invocations in the same session and
+// has to guess paths when chaining skills together.
+//
+// Design notes:
+// - Session-scoped: the sandbox path is resolved from the tool exec
+// context (`ToolExecContext.SessionID`). The LLM cannot pass an
+// arbitrary session ID.
+// - Directory guardrail: `path` must resolve underneath the session's
+// artifact output dir (`$WEKNORA_SKILL_OUTPUT_DIR`, default
+// `/workspace/output`). This keeps the tool aligned with the
+// directory ArtifactCollector already drains so anything the LLM
+// lists is guaranteed to also become a downloadable artifact.
+// - Read-only: this tool never creates, modifies or deletes anything
+// inside the sandbox. Writes still go through skill scripts.
+// - Graceful "no sandbox": if the session has never spawned a sandbox
+// yet (chat-only turn, or sandbox was reaped), the tool returns an
+// empty listing with a helpful message rather than an error, so the
+// LLM can decide to invoke a skill first.
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/agent/skills"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/utils"
+)
+
+// SandboxFileSource is the narrow, tool-facing subset of a session-aware
+// sandbox manager. In production it is satisfied by
+// *sandbox.SessionBoundManager; tests can stub it with an in-memory fake.
+//
+// Keeping the interface local to the tools package avoids leaking a
+// dependency on internal/application/service (which is a higher layer)
+// and mirrors the pattern used by ArtifactCollector.SandboxArtifactSource.
+type SandboxFileSource interface {
+ ListSessionFiles(ctx context.Context, sessionID, dir string) ([]sandbox.RemoteDirEntry, error)
+ StatSessionFile(ctx context.Context, sessionID, path string) (*sandbox.RemoteStatEntry, error)
+ ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
+}
+
+// defaultListSandboxMaxEntries caps a single list_sandbox_files call at
+// this many entries so a runaway directory can't blow up the LLM context.
+// Aligns with the "sane pagination" advice in the Anthropic tool-use guide.
+const (
+ defaultListSandboxMaxEntries = 200
+ maxListSandboxMaxEntries = 500
+)
+
+// Tool schema
+
+var listSandboxFilesTool = BaseTool{
+ name: ToolListSandboxFiles,
+ description: `List files produced by prior skill executions in the current session's sandbox.
+
+## Usage
+- Call this tool BEFORE invoking a follow-up skill that consumes a file
+ produced by an earlier skill in this session. Without this tool you are
+ guessing paths; with it you can see exactly what is available.
+- Also useful to confirm a skill actually produced the files it claims to
+ have generated (e.g. before telling the user "your report is ready").
+
+## When to Use
+- The user asks a follow-up question that references a file from a prior
+ turn ("summarize the report you generated", "improve the chart").
+- You are about to chain two skills where the second consumes an output
+ of the first.
+- You want to give the user a listing of everything the current session
+ has produced.
+
+## Path Rules
+- ` + "`path`" + ` is optional. When omitted, the tool lists the default artifact
+ output directory (` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `).
+- When provided, ` + "`path`" + ` MUST be underneath the artifact output directory.
+ Attempts to list arbitrary sandbox paths (e.g. ` + "`/etc`" + `, ` + "`/home`" + `) are
+ rejected.
+- Listing is recursive: sub-directories are traversed automatically and
+ only files are returned in the flat listing.
+
+## Returns
+- A list of entries with ` + "`path`" + ` (absolute, ready to pass to
+ ` + "`read_sandbox_file`" + `), ` + "`size`" + `, and ` + "`modified_at`" + ` timestamps.
+- When the session has never invoked a skill (no live sandbox yet), the
+ tool returns an empty listing with a clear "no sandbox" note — this is
+ not an error.`,
+ schema: utils.GenerateSchema[ListSandboxFilesInput](),
+}
+
+// ListSandboxFilesInput defines the input parameters for list_sandbox_files.
+type ListSandboxFilesInput struct {
+ // Path is the absolute path inside the sandbox to list. When empty
+ // the tool falls back to skills.ArtifactOutputDir(). Must be
+ // underneath the artifact output directory.
+ Path string `json:"path,omitempty" jsonschema:"Optional absolute sandbox path to list. Defaults to the session's artifact output directory. Must be underneath that directory."`
+ // MaxEntries caps the listing size to protect the LLM context.
+ // Zero uses defaultListSandboxMaxEntries.
+ MaxEntries int `json:"max_entries,omitempty" jsonschema:"Optional cap on the number of entries returned. Defaults to 200, hard-capped at 500. Use a smaller value when you only need to check whether a specific file exists."`
+}
+
+// ListSandboxFilesTool exposes SandboxFileSource.ListSessionFiles to the
+// agent as a read-only enumeration primitive.
+type ListSandboxFilesTool struct {
+ BaseTool
+ source SandboxFileSource
+}
+
+// NewListSandboxFilesTool constructs the tool. `source` MUST NOT be nil:
+// callers should feature-gate registration in the agent bootstrap when
+// the sandbox backend does not support per-session file inspection.
+func NewListSandboxFilesTool(source SandboxFileSource) *ListSandboxFilesTool {
+ return &ListSandboxFilesTool{
+ BaseTool: listSandboxFilesTool,
+ source: source,
+ }
+}
+
+// Execute enumerates files under the requested path inside the current
+// session's sandbox.
+func (t *ListSandboxFilesTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
+ logger.Infof(ctx, "[Tool][ListSandboxFiles] Execute started")
+
+ var input ListSandboxFilesInput
+ if err := json.Unmarshal(args, &input); err != nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("Failed to parse args: %v", err),
+ }, nil
+ }
+
+ if t.source == nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: "sandbox file inspection is not available in this deployment",
+ }, nil
+ }
+
+ // Resolve session ID from tool exec context (preferred) or the
+ // ambient context helper (fallback for direct unit tests).
+ sessionID := resolveSessionID(ctx)
+ if sessionID == "" {
+ return &types.ToolResult{
+ Success: false,
+ Error: "no session ID in context; list_sandbox_files must run inside an agent turn",
+ }, nil
+ }
+
+ // Resolve target directory. When the caller omits path we scan the
+ // same directory ArtifactCollector drains, guaranteeing everything
+ // the LLM sees will also be downloadable.
+ rootDir := skills.ArtifactOutputDir()
+ targetDir := strings.TrimSpace(input.Path)
+ if targetDir == "" {
+ targetDir = rootDir
+ } else {
+ clean := path.Clean(targetDir)
+ if !isUnderRoot(clean, rootDir) {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf(
+ "path %q is outside the artifact output directory %q; the LLM can only list files under the artifact output directory",
+ input.Path, rootDir,
+ ),
+ }, nil
+ }
+ targetDir = clean
+ }
+
+ maxEntries := input.MaxEntries
+ if maxEntries <= 0 {
+ maxEntries = defaultListSandboxMaxEntries
+ }
+ if maxEntries > maxListSandboxMaxEntries {
+ maxEntries = maxListSandboxMaxEntries
+ }
+
+ entries, err := t.source.ListSessionFiles(ctx, sessionID, targetDir)
+ if err != nil {
+ logger.Warnf(ctx, "[Tool][ListSandboxFiles] list failed: session=%s dir=%s err=%v",
+ sessionID, targetDir, err)
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("failed to list %s: %v", targetDir, err),
+ }, nil
+ }
+
+ // Deterministic ordering by path so multiple calls return the same
+ // pagination window even when the underlying backend does not
+ // guarantee ordering.
+ sort.SliceStable(entries, func(i, j int) bool {
+ return entries[i].Path < entries[j].Path
+ })
+
+ truncated := false
+ if len(entries) > maxEntries {
+ entries = entries[:maxEntries]
+ truncated = true
+ }
+
+ // Build human-readable output for the LLM. Machine-consumable data
+ // goes into ToolResult.Data.
+ var b strings.Builder
+ b.WriteString(fmt.Sprintf("=== Sandbox listing: %s ===\n\n", targetDir))
+ if len(entries) == 0 {
+ b.WriteString("No files found. Either no skill has produced output in this session yet, or the sandbox has been reaped.\n")
+ } else {
+ b.WriteString(fmt.Sprintf("Found %d file(s)", len(entries)))
+ if truncated {
+ b.WriteString(fmt.Sprintf(" (truncated to %d; increase max_entries to see more)", maxEntries))
+ }
+ b.WriteString(":\n\n")
+ for _, e := range entries {
+ b.WriteString(fmt.Sprintf("- %s (size=%d, modified=%s)\n",
+ e.Path, e.Size, formatSandboxModTime(e.ModTime)))
+ }
+ }
+
+ // Serialise entries for structured consumption.
+ items := make([]map[string]interface{}, 0, len(entries))
+ for _, e := range entries {
+ items = append(items, map[string]interface{}{
+ "name": e.Name,
+ "path": e.Path,
+ "size": e.Size,
+ "modified_at": formatSandboxModTime(e.ModTime),
+ })
+ }
+
+ logger.Infof(ctx, "[Tool][ListSandboxFiles] session=%s dir=%s count=%d truncated=%v",
+ sessionID, targetDir, len(items), truncated)
+
+ return &types.ToolResult{
+ Success: true,
+ Output: b.String(),
+ Data: map[string]interface{}{
+ "session_id": sessionID,
+ "path": targetDir,
+ "root": rootDir,
+ "entries": items,
+ "count": len(items),
+ "truncated": truncated,
+ },
+ }, nil
+}
+
+// Cleanup releases any resources.
+func (t *ListSandboxFilesTool) Cleanup(ctx context.Context) error {
+ return nil
+}
+
+// formatSandboxModTime renders a mod time in the RFC3339 shape the tool has
+// historically emitted. Zero times render as the empty string so LLM output
+// stays visually clean.
+func formatSandboxModTime(t time.Time) string {
+ if t.IsZero() {
+ return ""
+ }
+ return t.UTC().Format(time.RFC3339)
+}
+
+// resolveSessionID pulls the session ID out of the tool exec context (set
+// by the agent engine per tool call) with a fallback to the ambient
+// context helper used elsewhere in WeKnora.
+func resolveSessionID(ctx context.Context) string {
+ if meta, ok := ToolExecFromContext(ctx); ok && meta != nil && meta.SessionID != "" {
+ return meta.SessionID
+ }
+ if sid, ok := types.SessionIDFromContext(ctx); ok {
+ return sid
+ }
+ return ""
+}
+
+// isUnderRoot reports whether clean sits at or underneath root. Both
+// arguments must already be cleaned. This guardrail keeps the LLM from
+// listing paths outside the artifact output directory: even if a rogue
+// prompt asks for `/etc/passwd`, the tool refuses.
+func isUnderRoot(clean, root string) bool {
+ if clean == root {
+ return true
+ }
+ rootWithSep := root
+ if !strings.HasSuffix(rootWithSep, "/") {
+ rootWithSep += "/"
+ }
+ return strings.HasPrefix(clean, rootWithSep)
+}
diff --git a/internal/agent/tools/sandbox_read.go b/internal/agent/tools/sandbox_read.go
new file mode 100644
index 000000000..b1aac6f62
--- /dev/null
+++ b/internal/agent/tools/sandbox_read.go
@@ -0,0 +1,282 @@
+// Package tools — read_sandbox_file.
+//
+// Read-only tool that lets the LLM read the contents of a file the
+// current session's sandbox has produced. Pairs with list_sandbox_files:
+// the LLM lists first, then reads a specific path.
+//
+// Design notes:
+// - Session-scoped: path must belong to the current session's sandbox,
+// enforced by delegating to SandboxFileSource.ReadSessionFile which
+// itself takes the session ID from context.
+// - Directory guardrail: path must sit underneath the artifact output
+// directory. This makes the tool a companion to ArtifactCollector,
+// not a general-purpose filesystem reader (skills that need to peek
+// elsewhere should print via stdout).
+// - Stat-first size cap: files over 64 KiB are never downloaded. The
+// model receives metadata and uses shell_exec with sed/head/tail/grep/awk
+// to inspect only the relevant text section.
+// - Binary handling: binary bytes are never returned or base64-encoded into
+// model/client data. ArtifactCollector remains the download path.
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/agent/skills"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/utils"
+)
+
+// A read larger than this is refused before ReadSessionFile is called. The
+// caller may request a smaller ceiling, but never raise this hard limit.
+const (
+ defaultReadSandboxMaxBytes int64 = 64 * 1024
+ maxReadSandboxMaxBytes int64 = 64 * 1024
+)
+
+// Tool schema
+
+var readSandboxFileTool = BaseTool{
+ name: ToolReadSandboxFile,
+ description: `Read the contents of a file the current session's sandbox has produced.
+
+## Usage
+- Use in tandem with ` + "`list_sandbox_files`" + `: first list to find the file,
+ then read to inspect its content.
+- Handy when the user asks "what did that report say?" or you want to
+ quote a section of a skill-generated artifact.
+
+## When to Use
+- After a skill claims it wrote something and you want to confirm the
+ content matches expectations.
+- Before invoking a follow-up skill that consumes a file — you may want
+ to inspect a snippet to decide which skill to invoke or what arguments
+ to pass.
+- When the user asks you to summarise or edit a previously generated
+ artifact.
+
+## Path Rules
+- ` + "`path`" + ` MUST be an absolute path returned by ` + "`list_sandbox_files`" + `.
+- ` + "`path`" + ` MUST sit underneath the session's artifact output directory
+ (` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `). Reads
+ outside that directory are rejected.
+
+## Size Handling
+- Files larger than 64 KiB are NOT downloaded or returned.
+- For large text, use ` + "`shell_exec`" + ` with ` + "`sed -n`" + `, ` + "`head`" + `,
+ ` + "`tail`" + `, ` + "`grep`" + `, or ` + "`awk`" + ` to inspect a targeted section.
+- ` + "`max_bytes`" + ` may lower the refusal threshold but cannot exceed 65536.
+
+## Binary Files
+- Binary bytes are never returned to the model or embedded as base64.
+- Use the ArtifactCollector download attachment for PDFs, PPTX files, images,
+ archives, and other binary artifacts.`,
+ schema: utils.GenerateSchema[ReadSandboxFileInput](),
+}
+
+// ReadSandboxFileInput defines the input parameters for read_sandbox_file.
+type ReadSandboxFileInput struct {
+ // Path is the absolute path inside the sandbox to read. Required.
+ // Must sit underneath the artifact output directory.
+ Path string `json:"path" jsonschema:"Absolute path inside the sandbox. Must sit under the session's artifact output directory (typically /workspace/output). Get valid paths from list_sandbox_files."`
+ // MaxBytes is the largest file the tool may download. Zero uses 64 KiB;
+ // callers may lower but never raise the hard 64 KiB ceiling.
+ MaxBytes int64 `json:"max_bytes,omitempty" jsonschema:"Optional maximum file size to read. Defaults to 65536 bytes and is hard-capped at 65536. Larger files are not downloaded; use shell_exec with sed/head/tail/grep/awk."`
+}
+
+// ReadSandboxFileTool exposes SandboxFileSource.ReadSessionFile as a
+// safe, session-scoped read primitive.
+type ReadSandboxFileTool struct {
+ BaseTool
+ source SandboxFileSource
+}
+
+// NewReadSandboxFileTool constructs the tool. `source` MUST NOT be nil:
+// callers should feature-gate registration when the sandbox backend
+// does not support per-session file inspection.
+func NewReadSandboxFileTool(source SandboxFileSource) *ReadSandboxFileTool {
+ return &ReadSandboxFileTool{
+ BaseTool: readSandboxFileTool,
+ source: source,
+ }
+}
+
+// Execute reads the requested file (bounded by size cap) from the
+// current session's sandbox.
+func (t *ReadSandboxFileTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
+ logger.Infof(ctx, "[Tool][ReadSandboxFile] Execute started")
+
+ var input ReadSandboxFileInput
+ if err := json.Unmarshal(args, &input); err != nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("Failed to parse args: %v", err),
+ }, nil
+ }
+
+ if t.source == nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: "sandbox file inspection is not available in this deployment",
+ }, nil
+ }
+
+ trimmed := strings.TrimSpace(input.Path)
+ if trimmed == "" {
+ return &types.ToolResult{
+ Success: false,
+ Error: "path is required; call list_sandbox_files first to discover valid paths",
+ }, nil
+ }
+
+ sessionID := resolveSessionID(ctx)
+ if sessionID == "" {
+ return &types.ToolResult{
+ Success: false,
+ Error: "no session ID in context; read_sandbox_file must run inside an agent turn",
+ }, nil
+ }
+
+ // Enforce that the path sits underneath the artifact output dir.
+ // This mirrors list_sandbox_files' rule so the LLM sees a
+ // consistent "reachable surface".
+ rootDir := skills.ArtifactOutputDir()
+ clean := path.Clean(trimmed)
+ if !isUnderRoot(clean, rootDir) {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf(
+ "path %q is outside the artifact output directory %q; only files produced under that directory can be read",
+ input.Path, rootDir,
+ ),
+ }, nil
+ }
+
+ // Resolve the byte cap for this call.
+ maxBytes := input.MaxBytes
+ if maxBytes <= 0 {
+ maxBytes = defaultReadSandboxMaxBytes
+ }
+ if maxBytes > maxReadSandboxMaxBytes {
+ maxBytes = maxReadSandboxMaxBytes
+ }
+
+ stat, err := t.source.StatSessionFile(ctx, sessionID, clean)
+ if err != nil {
+ logger.Warnf(ctx, "[Tool][ReadSandboxFile] stat failed: session=%s path=%s err=%v",
+ sessionID, clean, err)
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("failed to inspect %s before reading: %v", clean, err),
+ }, nil
+ }
+ if stat == nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("file not found: %s", clean),
+ }, nil
+ }
+ if stat.Type == sandbox.RemoteEntryDir {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("path is a directory, not a file: %s", clean),
+ }, nil
+ }
+ if stat.Size > maxBytes {
+ logger.Infof(ctx, "[Tool][ReadSandboxFile] refused oversize file: session=%s path=%s size=%d limit=%d",
+ sessionID, clean, stat.Size, maxBytes)
+ return oversizedSandboxFileResult(sessionID, clean, rootDir, stat.Size, maxBytes), nil
+ }
+
+ data, err := t.source.ReadSessionFile(ctx, sessionID, clean)
+ if err != nil {
+ logger.Warnf(ctx, "[Tool][ReadSandboxFile] read failed: session=%s path=%s err=%v",
+ sessionID, clean, err)
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("failed to read %s: %v", clean, err),
+ }, nil
+ }
+
+ total := int64(len(data))
+ // The file may have grown between Stat and Read. Do not return a prefix
+ // from a full oversized download as if it were an intentional partial read.
+ if total > maxBytes {
+ logger.Warnf(ctx, "[Tool][ReadSandboxFile] file grew during read: session=%s path=%s size=%d limit=%d",
+ sessionID, clean, total, maxBytes)
+ return oversizedSandboxFileResult(sessionID, clean, rootDir, total, maxBytes), nil
+ }
+
+ binary := isBinaryShellOutput(string(data))
+
+ // Build LLM-facing output. Text is inlined only once in Output; binary
+ // bytes are suppressed and represented by metadata.
+ var b strings.Builder
+ b.WriteString(fmt.Sprintf("=== Sandbox file: %s ===\n\n", clean))
+ b.WriteString(fmt.Sprintf("size=%d bytes, returned=%d bytes\n", total, len(data)))
+
+ resultData := map[string]interface{}{
+ "session_id": sessionID,
+ "path": clean,
+ "root": rootDir,
+ "size": total,
+ "returned_bytes": len(data),
+ "truncated": false,
+ "binary": binary,
+ }
+
+ if binary {
+ b.WriteString("binary file — content suppressed; use the artifact attachment to download it.\n")
+ } else {
+ b.WriteString("\n```\n")
+ b.Write(data)
+ if len(data) > 0 && data[len(data)-1] != '\n' {
+ b.WriteString("\n")
+ }
+ b.WriteString("```\n")
+ }
+
+ logger.Infof(ctx, "[Tool][ReadSandboxFile] session=%s path=%s size=%d returned=%d binary=%v",
+ sessionID, clean, total, len(data), binary)
+
+ return &types.ToolResult{
+ Success: true,
+ Output: b.String(),
+ Data: resultData,
+ }, nil
+}
+
+func oversizedSandboxFileResult(sessionID, filePath, rootDir string, size, limit int64) *types.ToolResult {
+ output := fmt.Sprintf(
+ "=== Sandbox file too large to read: %s ===\n\n"+
+ "size=%d bytes, limit=%d bytes, returned=0 bytes\n\n"+
+ "The file was not downloaded. Use shell_exec with sed -n, head, tail, grep, or awk "+
+ "to inspect only the relevant text section. Binary files remain available through the artifact attachment.\n",
+ filePath, size, limit,
+ )
+ return &types.ToolResult{
+ Success: true,
+ Output: output,
+ Data: map[string]interface{}{
+ "session_id": sessionID,
+ "path": filePath,
+ "root": rootDir,
+ "size": size,
+ "limit": limit,
+ "returned_bytes": 0,
+ "truncated": true,
+ "read_refused": true,
+ },
+ }
+}
+
+// Cleanup releases any resources.
+func (t *ReadSandboxFileTool) Cleanup(ctx context.Context) error {
+ return nil
+}
diff --git a/internal/agent/tools/sandbox_read_test.go b/internal/agent/tools/sandbox_read_test.go
new file mode 100644
index 000000000..41a299961
--- /dev/null
+++ b/internal/agent/tools/sandbox_read_test.go
@@ -0,0 +1,125 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type fakeSandboxFileSource struct {
+ stat *sandbox.RemoteStatEntry
+ statErr error
+ data []byte
+ readErr error
+ entries []sandbox.RemoteDirEntry
+ statCalls int
+ readCalls int
+}
+
+func (f *fakeSandboxFileSource) ListSessionFiles(context.Context, string, string) ([]sandbox.RemoteDirEntry, error) {
+ return f.entries, nil
+}
+
+func (f *fakeSandboxFileSource) StatSessionFile(context.Context, string, string) (*sandbox.RemoteStatEntry, error) {
+ f.statCalls++
+ return f.stat, f.statErr
+}
+
+func (f *fakeSandboxFileSource) ReadSessionFile(context.Context, string, string) ([]byte, error) {
+ f.readCalls++
+ return f.data, f.readErr
+}
+
+func sandboxFileTestContext() context.Context {
+ return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "session-1"})
+}
+
+func TestReadSandboxFileRefusesOversizeBeforeRead(t *testing.T) {
+ source := &fakeSandboxFileSource{
+ stat: &sandbox.RemoteStatEntry{Path: "/workspace/output/large.txt", Type: sandbox.RemoteEntryFile, Size: maxReadSandboxMaxBytes + 1},
+ data: []byte("must not be read"),
+ }
+
+ result, err := NewReadSandboxFileTool(source).Execute(
+ sandboxFileTestContext(),
+ json.RawMessage(`{"path":"/workspace/output/large.txt","max_bytes":999999}`),
+ )
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Equal(t, 1, source.statCalls)
+ assert.Zero(t, source.readCalls)
+ assert.Equal(t, true, result.Data["read_refused"])
+ assert.Equal(t, int64(maxReadSandboxMaxBytes+1), result.Data["size"])
+ assert.Contains(t, result.Output, "shell_exec")
+}
+
+func TestReadSandboxFileReturnsSmallTextOnlyInOutput(t *testing.T) {
+ content := []byte("hello sandbox\n")
+ source := &fakeSandboxFileSource{
+ stat: &sandbox.RemoteStatEntry{Path: "/workspace/output/report.txt", Type: sandbox.RemoteEntryFile, Size: int64(len(content))},
+ data: content,
+ }
+
+ result, err := NewReadSandboxFileTool(source).Execute(
+ sandboxFileTestContext(),
+ json.RawMessage(`{"path":"/workspace/output/report.txt"}`),
+ )
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Equal(t, 1, source.readCalls)
+ assert.Contains(t, result.Output, string(content))
+ _, duplicated := result.Data["content"]
+ assert.False(t, duplicated)
+}
+
+func TestReadSandboxFileSuppressesBinaryWithoutBase64(t *testing.T) {
+ content := []byte{0xff, 0x00, 0x01}
+ source := &fakeSandboxFileSource{
+ stat: &sandbox.RemoteStatEntry{Path: "/workspace/output/image.bin", Type: sandbox.RemoteEntryFile, Size: int64(len(content))},
+ data: content,
+ }
+
+ result, err := NewReadSandboxFileTool(source).Execute(
+ sandboxFileTestContext(),
+ json.RawMessage(`{"path":"/workspace/output/image.bin"}`),
+ )
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Equal(t, true, result.Data["binary"])
+ assert.NotContains(t, result.Output, string(content))
+ assert.Contains(t, result.Output, "content suppressed")
+ _, hasBase64 := result.Data["content_base64"]
+ assert.False(t, hasBase64)
+}
+
+func TestListSandboxFilesHardCapsEntries(t *testing.T) {
+ entries := make([]sandbox.RemoteDirEntry, 600)
+ for i := range entries {
+ entries[i] = sandbox.RemoteDirEntry{
+ Name: fmt.Sprintf("%03d.txt", i),
+ Path: fmt.Sprintf("/workspace/output/%03d.txt", i),
+ Type: sandbox.RemoteEntryFile,
+ }
+ }
+ source := &fakeSandboxFileSource{entries: entries}
+
+ result, err := NewListSandboxFilesTool(source).Execute(
+ sandboxFileTestContext(),
+ json.RawMessage(`{"max_entries":999999}`),
+ )
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Equal(t, maxListSandboxMaxEntries, result.Data["count"])
+ assert.Equal(t, true, result.Data["truncated"])
+ assert.Equal(t, maxListSandboxMaxEntries, strings.Count(result.Output, "\n- "))
+}
diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go
new file mode 100644
index 000000000..43bf00437
--- /dev/null
+++ b/internal/agent/tools/shell_exec.go
@@ -0,0 +1,507 @@
+// Package tools — shell_exec.
+//
+// General shell command execution primitive for the agent. The LLM can freely
+// explore and operate inside its session-scoped Cube MicroVM: inspect files,
+// transform data, run programs, install dependencies, and prepare or verify
+// skill outputs.
+//
+// Design notes:
+//
+// - Cube-only capability: registration is feature-gated on the sandbox
+// backend exposing SandboxCommandExecutor. Docker / Local backends do
+// NOT satisfy the interface, preserving their existing stateless
+// security model. shell_exec never runs on the WeKnora host.
+// - Session-scoped: the sandbox is resolved from ToolExecContext.SessionID
+// so the LLM cannot execute against a foreign session, and installed
+// dependencies persist across subsequent tool calls in the same session.
+// - Non-zero exit is a normal signal, not an error: pip install failures,
+// missing binaries, etc. are all valid results the LLM must inspect.
+// Only wire-level errors (sandbox unreachable, timeout) surface as
+// ToolResult.Success = false.
+// - Output truncation: shell installers produce thousands of lines that
+// would blow up the LLM context. We keep the head (leading messages)
+// and the tail (final errors) with an ellipsis marker so the tail —
+// usually the most informative segment — is preserved.
+// - Command shape blacklist: the sandbox is throwaway, but we still refuse
+// obviously destructive patterns (rm -rf /, fork bombs, mkfs...) to
+// protect the LLM from its own hallucinations.
+// - No backgrounding, no stdin: matches the confirmed product decisions.
+// Trailing '&' and 'nohup' are rejected up-front to avoid orphaned
+// processes inside the sandbox.
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path"
+ "regexp"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/utils"
+)
+
+// SandboxCommandExecutor is the narrow, tool-facing subset of a session-aware
+// sandbox manager that supports executing arbitrary shell commands. In
+// production it is satisfied by *sandbox.SessionBoundManager; tests can stub
+// it with an in-memory fake. Kept local to the tools package for the same
+// reason as SandboxFileSource — no dependency leak into higher layers.
+type SandboxCommandExecutor interface {
+ ExecShellCommand(
+ ctx context.Context,
+ sessionID string,
+ command string,
+ workDir string,
+ timeout time.Duration,
+ env map[string]string,
+ ) (*sandbox.ExecuteResult, error)
+}
+
+// Limits — kept generous enough for `pip install tensorflow` while still
+// bounding the LLM context blast radius.
+const (
+ // defaultShellExecWorkDir is where commands land when the caller omits
+ // work_dir. Matches CubeSandbox.Execute's remote directory convention.
+ defaultShellExecWorkDir = "/workspace"
+ // defaultShellExecTimeout is applied when the caller omits timeout_sec.
+ // 120s is enough for most pip installs; heavier installs can opt in via
+ // timeout_sec up to shellExecMaxTimeout.
+ defaultShellExecTimeout = 120 * time.Second
+ // shellExecMaxTimeout hard-caps timeout_sec. Ten minutes covers even the
+ // slow "install libreoffice" case without letting a runaway command
+ // pin the session's sandbox for hours.
+ shellExecMaxTimeout = 10 * time.Minute
+ // shellExecMaxCommandBytes rejects excessively long command strings.
+ // Real skill setup scripts fit comfortably under 8 KiB.
+ shellExecMaxCommandBytes = 8 * 1024
+ // max_output_bytes controls stdout only. Stderr uses a smaller independent
+ // budget so verbose failures cannot consume the entire tool result.
+ defaultShellExecOutputBytes = 16 * 1024
+ maxShellExecOutputBytes = 64 * 1024
+ defaultShellExecStderrBytes = 8 * 1024
+ maxShellExecStderrBytes = 16 * 1024
+ maxShellExecErrorBytes = 4 * 1024
+ maxShellExecVisibleBytes = 64 * 1024
+)
+
+// Blacklist patterns. These are cheap sanity checks, not a security
+// perimeter — the Cube MicroVM session isolation is the real perimeter.
+// The intent is to prevent the LLM from bricking its own session with a
+// hallucinated one-liner (e.g. `rm -rf /`).
+//
+// Each entry is a compiled regexp; we return the first matching entry's
+// name in the error so the LLM sees exactly why its command was rejected
+// and can adjust.
+var shellExecBlacklist = []struct {
+ name string
+ re *regexp.Regexp
+}{
+ // `rm -rf /` and variants (including `rm -Rf --no-preserve-root /`).
+ // Reject any rm with a recursive+force flag targeting the filesystem
+ // root. We intentionally do NOT block `rm -rf /workspace/foo` — a
+ // skill legitimately might clean up its scratch directory.
+ {name: "rm_root", re: regexp.MustCompile(`(?i)\brm\s+(?:-[a-z]*[rR][a-z]*[fF][a-z]*|-[a-z]*[fF][a-z]*[rR][a-z]*|--recursive[^;|&]*--force|--force[^;|&]*--recursive)\s+(?:--no-preserve-root\s+)?/(?:\s|$)`)},
+ // Classic fork bomb.
+ {name: "fork_bomb", re: regexp.MustCompile(`:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:`)},
+ // Filesystem-format / raw-device writes.
+ {name: "mkfs", re: regexp.MustCompile(`(?i)\bmkfs(\.[a-z0-9]+)?\b`)},
+ {name: "dd_to_device", re: regexp.MustCompile(`(?i)\bdd\b[^;|&]*\bof=/dev/`)},
+ // Host-level power management. Even inside a MicroVM these serve no
+ // legitimate skill purpose and would just tear down the session.
+ {name: "shutdown", re: regexp.MustCompile(`(?i)\b(shutdown|reboot|halt|poweroff)\b`)},
+ // Explicit backgrounding is a product decision (see file header). Trailing
+ // `&` (but not `&&`) or a `nohup` prefix indicates the LLM tried to
+ // detach a process.
+ {name: "background_amp", re: regexp.MustCompile(`(?:^|[^&])&\s*(?:#.*)?$`)},
+ {name: "nohup", re: regexp.MustCompile(`(?i)(^|[;|&\s])nohup\b`)},
+}
+
+// Tool schema
+
+var shellExecTool = BaseTool{
+ name: ToolShellExec,
+ description: `Run a shell command inside the current session's isolated remote sandbox.
+
+## Usage
+- Use freely to explore and operate inside the sandbox: inspect files, search
+ content, transform data, run programs, manage dependencies, install system packages and verify outputs.
+- If a 'command not found' error occurs, attempt to resolve it by running ` + "`apt-get update && apt-get install -y <package>`" + `, or use any other appropriate method to install the missing command.
+- User-uploaded files listed in ` + "`<sandbox_attachments>`" + ` are restored under
+ ` + "`/workspace/input`" + `. Treat them as read-only inputs; write generated files
+ under ` + "`/workspace/output`" + `.
+- Prefer standard Unix tools for filesystem work: ` + "`find`" + ` / ` + "`file`" + ` to discover
+ files and types; ` + "`cat`" + ` / ` + "`head`" + ` / ` + "`tail`" + ` / ` + "`sed`" + ` to inspect
+ text; ` + "`grep`" + ` / ` + "`awk`" + ` to search and process it.
+- Install skill dependencies (` + "`pip install ...`" + `, ` + "`apt-get update && apt-get install -y ...`" + `,
+ ` + "`npm i ...`" + `) before calling ` + "`execute_skill_script`" + ` when required.
+
+## When to Use
+- Whenever executing a command is the most direct way to complete the task.
+- To inspect any text file or directory in the sandbox, including system paths.
+- To chain shell pipelines, unpack archives, compile or run code, and prepare
+ intermediate files for later commands or skills.
+
+## When NOT to Use
+- DO NOT use this to run a skill's main script — use ` + "`execute_skill_script`" + `
+ which handles skill lookup, artifact collection, and proper interpreter
+ selection.
+- DO NOT try to background processes (` + "`&`" + ` at the end, ` + "`nohup`" + `). Sandbox
+ execution is synchronous.
+
+## Parameters
+- ` + "`command`" + ` (required): the shell one-liner to run under ` + "`/bin/bash -l -c`" + `.
+ Supports pipes, redirects, ` + "`&&`" + ` / ` + "`||`" + ` chaining.
+- ` + "`work_dir`" + ` (optional): working directory, defaults to ` + "`/workspace`" + `.
+ Created on demand if it doesn't exist.
+- ` + "`timeout_sec`" + ` (optional): per-call timeout in seconds. Defaults to 120,
+ capped at 600. Large installs (LibreOffice, TensorFlow) may need the cap.
+- ` + "`max_output_bytes`" + ` (optional): maximum bytes returned from stdout.
+ Defaults to 16384, capped at 65536. Stderr is independently limited to 8192
+ bytes by default; ` + "`max_stderr_bytes`" + ` may raise it to at most 16384.
+ The complete visible result is always capped at 65536 bytes.
+- ` + "`env`" + ` (optional): extra environment variables merged on top of the
+ sandbox's base env, e.g. ` + "`{\"PIP_INDEX_URL\": \"https://mirrors.tencent.com/pypi/simple\"}`" + `.
+
+## Returns
+- ` + "`exit_code`" + `: 0 on success, non-zero on failure. Non-zero is NOT a tool
+ error — the tool call succeeds; you should read stderr and decide what to
+ do next (retry, adjust arguments, tell the user).
+- ` + "`stdout`" + ` / ` + "`stderr`" + `: captured output, truncated to preserve context
+ budget. The tail is preserved when truncation happens, since the final
+ lines usually carry the crucial error message.
+- Binary output is never returned to the model. Store binary files under
+ ` + "`/workspace/output`" + ` so ArtifactCollector can expose them for download.
+- ` + "`duration_ms`" + `: wall-clock execution time.
+
+## Safety
+- The command runs inside a session-scoped MicroVM: destructive commands
+ only affect this session's sandbox, never the host or other sessions.
+- Obviously destructive patterns (` + "`rm -rf /`" + `, fork bombs, ` + "`mkfs`" + `, ` + "`shutdown`" + `)
+ are refused up-front. Cleaning up your own scratch dir (e.g.
+ ` + "`rm -rf /workspace/tmp`" + `) is fine.
+- Only available when the sandbox backend is Remote SandBox. On Docker / Local
+ deployments this tool is not registered.`,
+ schema: utils.GenerateSchema[ShellExecInput](),
+}
+
+// ShellExecInput defines the input parameters for shell_exec.
+type ShellExecInput struct {
+ // Command is the shell command to execute. Runs under `/bin/bash -l -c`.
+ Command string `json:"command" jsonschema:"Shell command to execute (single line, supports pipes and && chaining). Runs under /bin/bash -l -c."`
+ // WorkDir is the working directory for the command; defaults to /workspace.
+ WorkDir string `json:"work_dir,omitempty" jsonschema:"Working directory for the command. Defaults to /workspace. Created on demand if missing."`
+ // TimeoutSec caps execution time. Zero uses the default (120s); the
+ // value is hard-capped at 600s regardless of what the LLM requests.
+ TimeoutSec int `json:"timeout_sec,omitempty" jsonschema:"Per-call timeout in seconds. Defaults to 120, hard-capped at 600."`
+ // MaxOutputBytes caps returned stdout. Stderr has an independent smaller
+ // fixed budget, and the complete model-visible output is capped at 64 KiB.
+ MaxOutputBytes int `json:"max_output_bytes,omitempty" jsonschema:"Maximum bytes returned from stdout. Defaults to 16384, hard-capped at 65536. Stderr defaults to 8192 and is hard-capped at 16384; total visible output is hard-capped at 65536."`
+ // MaxStderrBytes caps returned stderr independently from stdout.
+ MaxStderrBytes int `json:"max_stderr_bytes,omitempty" jsonschema:"Maximum bytes returned from stderr. Defaults to 8192, hard-capped at 16384."`
+ // Env carries extra environment variables merged into the shell's env.
+ Env map[string]string `json:"env,omitempty" jsonschema:"Optional extra environment variables, e.g. {\"PIP_INDEX_URL\":\"https://mirrors.example.com/pypi/simple\"}."`
+}
+
+// ShellExecTool executes shell commands inside the session's sandbox.
+type ShellExecTool struct {
+ BaseTool
+ executor SandboxCommandExecutor
+}
+
+// NewShellExecTool constructs the tool. `executor` MUST NOT be nil:
+// callers should feature-gate registration when the sandbox backend
+// does not support ad-hoc shell execution (i.e. is not Cube).
+func NewShellExecTool(executor SandboxCommandExecutor) *ShellExecTool {
+ return &ShellExecTool{
+ BaseTool: shellExecTool,
+ executor: executor,
+ }
+}
+
+// OutputLimitChars lets ToolRegistry preserve shell_exec's explicitly bounded,
+// caller-configurable output instead of applying its lower generic limit again.
+func (t *ShellExecTool) OutputLimitChars(args json.RawMessage) int {
+ return maxShellExecVisibleBytes
+}
+
+// Execute runs the requested command inside the current session's sandbox.
+func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
+ logger.Infof(ctx, "[Tool][ShellExec] Execute started")
+
+ var input ShellExecInput
+ if err := json.Unmarshal(args, &input); err != nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("Failed to parse args: %v", err),
+ }, nil
+ }
+
+ if t.executor == nil {
+ return &types.ToolResult{
+ Success: false,
+ Error: "shell_exec is not available in this deployment (remote sandbox required)",
+ }, nil
+ }
+
+ command := strings.TrimSpace(input.Command)
+ if command == "" {
+ return &types.ToolResult{
+ Success: false,
+ Error: "command is required",
+ }, nil
+ }
+ if len(command) > shellExecMaxCommandBytes {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("command too long (%d bytes; max %d)", len(command), shellExecMaxCommandBytes),
+ }, nil
+ }
+ if reason := checkShellExecBlacklist(command); reason != "" {
+ logger.Warnf(ctx, "[Tool][ShellExec] rejected by blacklist: %s command=%q", reason, command)
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf("command rejected by shell_exec safety guard: %s", reason),
+ }, nil
+ }
+
+ sessionID := resolveSessionID(ctx)
+ if sessionID == "" {
+ return &types.ToolResult{
+ Success: false,
+ Error: "no session ID in context; shell_exec must run inside an agent turn",
+ }, nil
+ }
+
+ workDir := strings.TrimSpace(input.WorkDir)
+ if workDir == "" {
+ workDir = defaultShellExecWorkDir
+ }
+ cleanWorkDir := path.Clean(workDir)
+ if !isUnderRoot(cleanWorkDir, defaultShellExecWorkDir) {
+ return &types.ToolResult{
+ Success: false,
+ Error: fmt.Sprintf(
+ "work_dir %q is outside the sandbox workspace %q",
+ input.WorkDir, defaultShellExecWorkDir,
+ ),
+ }, nil
+ }
+ workDir = cleanWorkDir
+
+ timeout := defaultShellExecTimeout
+ if input.TimeoutSec > 0 {
+ timeout = time.Duration(input.TimeoutSec) * time.Second
+ }
+ if timeout > shellExecMaxTimeout {
+ timeout = shellExecMaxTimeout
+ }
+
+ logger.Infof(ctx, "[Tool][ShellExec] session=%s work_dir=%s timeout=%s command=%q",
+ sessionID, workDir, timeout, command)
+
+ res, err := t.executor.ExecShellCommand(ctx, sessionID, command, workDir, timeout, input.Env)
+ if err != nil {
+ logger.Warnf(ctx, "[Tool][ShellExec] execution error: session=%s err=%v", sessionID, err)
+ errorText, _ := truncateShellStream(fmt.Sprintf("shell_exec failed: %v", err), maxShellExecErrorBytes)
+ return &types.ToolResult{
+ Success: false,
+ Error: errorText,
+ }, nil
+ }
+
+ outputLimit := resolveShellOutputLimit(input.MaxOutputBytes)
+ stderrLimit := resolveShellStderrLimit(input.MaxStderrBytes)
+ stdout, stdoutTruncated, stdoutBinary := prepareShellStream(res.Stdout, outputLimit)
+ stderr, stderrTruncated, stderrBinary := prepareShellStream(res.Stderr, stderrLimit)
+ errorText, errorTruncated := truncateShellStream(res.Error, maxShellExecErrorBytes)
+ truncated := stdoutTruncated || stderrTruncated || errorTruncated
+
+ // Human-readable summary for the LLM.
+ var b strings.Builder
+ b.WriteString(fmt.Sprintf("=== Shell Exec (session=%s) ===\n\n", sessionID))
+ b.WriteString(fmt.Sprintf("**Command**: `%s`\n", command))
+ b.WriteString(fmt.Sprintf("**Work Dir**: %s\n", workDir))
+ b.WriteString(fmt.Sprintf("**Exit Code**: %d\n", res.ExitCode))
+ b.WriteString(fmt.Sprintf("**Duration**: %v\n", res.Duration))
+ if res.Killed {
+ b.WriteString("**Killed**: yes (timeout or terminated)\n")
+ }
+ if truncated {
+ b.WriteString("**Truncated**: yes (head+tail kept; run `tail -n 200 <logfile>` inside the sandbox for full output)\n")
+ }
+ if stdoutBinary || stderrBinary {
+ b.WriteString("**Binary Output Suppressed**: yes (write binary files to the artifact output directory for download)\n")
+ }
+ b.WriteString("\n")
+
+ if stdout != "" {
+ b.WriteString("## Stdout\n\n```\n")
+ b.WriteString(stdout)
+ if !strings.HasSuffix(stdout, "\n") {
+ b.WriteString("\n")
+ }
+ b.WriteString("```\n\n")
+ }
+ if stderr != "" {
+ b.WriteString("## Stderr\n\n```\n")
+ b.WriteString(stderr)
+ if !strings.HasSuffix(stderr, "\n") {
+ b.WriteString("\n")
+ }
+ b.WriteString("```\n\n")
+ }
+ if errorText != "" {
+ b.WriteString("## Error\n\n")
+ b.WriteString(errorText)
+ b.WriteString("\n")
+ }
+ visibleOutput := b.String()
+ visibleOutput, totalTruncated := truncateShellStream(visibleOutput, maxShellExecVisibleBytes)
+ truncated = truncated || errorTruncated || totalTruncated
+
+ // The tool call itself succeeds even when the shell command exits non-zero:
+ // the LLM needs stderr/exit_code as first-class signals to iterate. We
+ // only mark Success=false when a wire-level problem prevented the command
+ // from running at all (already handled above via err != nil).
+ resultData := map[string]interface{}{
+ "session_id": sessionID,
+ "command": command,
+ "work_dir": workDir,
+ "exit_code": res.ExitCode,
+ "stdout": stdout,
+ "stderr": stderr,
+ "duration_ms": res.Duration.Milliseconds(),
+ "killed": res.Killed,
+ "truncated": truncated,
+ "stdout_truncated": stdoutTruncated,
+ "stderr_truncated": stderrTruncated,
+ "stdout_binary": stdoutBinary,
+ "stderr_binary": stderrBinary,
+ "stdout_bytes": len(res.Stdout),
+ "stderr_bytes": len(res.Stderr),
+ "stdout_original_bytes": len(res.Stdout),
+ "stdout_returned_bytes": len(stdout),
+ "stderr_original_bytes": len(res.Stderr),
+ "stderr_returned_bytes": len(stderr),
+ "error_original_bytes": len(res.Error),
+ "error_returned_bytes": len(errorText),
+ "error_truncated": errorTruncated,
+ "total_truncated": totalTruncated,
+ "visible_original_bytes": b.Len(),
+ "visible_returned_bytes": len(visibleOutput),
+ "max_output_bytes": outputLimit,
+ "max_stderr_bytes": stderrLimit,
+ }
+
+ logger.Infof(ctx, "[Tool][ShellExec] session=%s exit=%d duration=%v killed=%v truncated=%v",
+ sessionID, res.ExitCode, res.Duration, res.Killed, truncated)
+
+ return &types.ToolResult{
+ Success: true,
+ Output: visibleOutput,
+ Data: resultData,
+ }, nil
+}
+
+func resolveShellOutputLimit(requested int) int {
+ if requested <= 0 {
+ return defaultShellExecOutputBytes
+ }
+ if requested > maxShellExecOutputBytes {
+ return maxShellExecOutputBytes
+ }
+ return requested
+}
+
+func resolveShellStderrLimit(requested int) int {
+ if requested <= 0 {
+ return defaultShellExecStderrBytes
+ }
+ if requested > maxShellExecStderrBytes {
+ return maxShellExecStderrBytes
+ }
+ return requested
+}
+
+// prepareShellStream suppresses binary data before it can enter ToolResult
+// Output or Data. Text streams are bounded using head+tail preservation.
+func prepareShellStream(s string, limit int) (output string, truncated, binary bool) {
+ if isBinaryShellOutput(s) {
+ return "", false, true
+ }
+ output, truncated = truncateShellStream(s, limit)
+ return output, truncated, false
+}
+
+func isBinaryShellOutput(s string) bool {
+ if s == "" {
+ return false
+ }
+ if !utf8.ValidString(s) || strings.IndexByte(s, 0) >= 0 {
+ return true
+ }
+ // Any non-text control byte is enough to suppress the stream. ANSI terminal
+ // escapes remain allowed so ordinary colored command output stays readable.
+ for _, r := range s {
+ if r < 0x20 && r != '\n' && r != '\r' && r != '\t' &&
+ r != '\b' && r != '\f' && r != 0x1b {
+ return true
+ }
+ }
+ return false
+}
+
+// Cleanup releases any resources.
+func (t *ShellExecTool) Cleanup(ctx context.Context) error {
+ return nil
+}
+
+// checkShellExecBlacklist reports a non-empty reason string when command
+// matches one of the blacklist patterns. Returns "" for allowed commands.
+func checkShellExecBlacklist(command string) string {
+ for _, entry := range shellExecBlacklist {
+ if entry.re.MatchString(command) {
+ return entry.name
+ }
+ }
+ return ""
+}
+
+// truncateShellStream reduces s to at most limit bytes by keeping the head
+// and tail of the stream. The tail is prioritised because the final lines
+// of a shell run almost always carry the actionable diagnostic (success
+// marker, traceback, "ERROR: could not find matching distribution").
+//
+// Returns the (possibly truncated) content and a flag indicating whether
+// any trimming happened.
+func truncateShellStream(s string, limit int) (string, bool) {
+ if limit <= 0 || len(s) <= limit {
+ return s, false
+ }
+ // Include the marker inside the byte budget. Its omitted-byte count depends
+ // on the retained size, so compute it once, then recalculate the final split.
+ marker := fmt.Sprintf("\n...[truncated %d bytes]...\n", len(s)-limit)
+ if len(marker) >= limit {
+ return s[len(s)-limit:], true
+ }
+ kept := limit - len(marker)
+ head := kept / 4
+ tail := kept - head
+ marker = fmt.Sprintf("\n...[truncated %d bytes]...\n", len(s)-head-tail)
+ if len(marker) != limit-kept {
+ kept = limit - len(marker)
+ head = kept / 4
+ tail = kept - head
+ }
+ var b strings.Builder
+ b.Grow(limit)
+ b.WriteString(s[:head])
+ b.WriteString(marker)
+ b.WriteString(s[len(s)-tail:])
+ return b.String(), true
+}
diff --git a/internal/agent/tools/shell_exec_test.go b/internal/agent/tools/shell_exec_test.go
new file mode 100644
index 000000000..bdb74247e
--- /dev/null
+++ b/internal/agent/tools/shell_exec_test.go
@@ -0,0 +1,174 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type fakeShellExecutor struct {
+ result *sandbox.ExecuteResult
+ err error
+ timeout time.Duration
+}
+
+func (f *fakeShellExecutor) ExecShellCommand(
+ _ context.Context,
+ _ string,
+ _ string,
+ _ string,
+ timeout time.Duration,
+ _ map[string]string,
+) (*sandbox.ExecuteResult, error) {
+ f.timeout = timeout
+ if f.err != nil {
+ return nil, f.err
+ }
+ if f.result == nil {
+ return &sandbox.ExecuteResult{ExitCode: 0}, nil
+ }
+ return f.result, nil
+}
+
+func shellExecTestContext() context.Context {
+ return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "session-1"})
+}
+
+func TestShellExecRejectsWorkDirOutsideWorkspace(t *testing.T) {
+ executor := &fakeShellExecutor{}
+ tool := NewShellExecTool(executor)
+
+ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
+ `{"command":"pwd","work_dir":"/etc"}`,
+ ))
+
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Contains(t, result.Error, "outside the sandbox workspace")
+ assert.Equal(t, time.Duration(0), executor.timeout)
+}
+
+func TestShellExecTimeoutHonorsAndCapsRequestedValue(t *testing.T) {
+ executor := &fakeShellExecutor{}
+ tool := NewShellExecTool(executor)
+
+ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
+ `{"command":"sleep 1","timeout_sec":999}`,
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Equal(t, shellExecMaxTimeout, executor.timeout)
+}
+
+func TestShellExecConfigurableOutputAndRegistryOverride(t *testing.T) {
+ content := strings.Repeat("x", 24*1024)
+ executor := &fakeShellExecutor{result: &sandbox.ExecuteResult{
+ Stdout: content,
+ ExitCode: 0,
+ }}
+ registry := NewToolRegistry()
+ registry.RegisterTool(NewShellExecTool(executor))
+
+ result, err := registry.ExecuteTool(shellExecTestContext(), ToolShellExec, json.RawMessage(
+ `{"command":"cat large.txt","max_output_bytes":32768}`,
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Contains(t, result.Output, content)
+ assert.NotContains(t, result.Output, "output truncated")
+ assert.Equal(t, 32768, result.Data["max_output_bytes"])
+}
+
+func TestShellExecOutputLimitIsHardCapped(t *testing.T) {
+ tool := NewShellExecTool(&fakeShellExecutor{})
+
+ limit := tool.OutputLimitChars(json.RawMessage(`{"max_output_bytes":999999}`))
+
+ assert.Equal(t, maxShellExecVisibleBytes, limit)
+}
+
+func TestShellExecSuppressesBinaryStreams(t *testing.T) {
+ binary := "prefix\x00\x01payload"
+ executor := &fakeShellExecutor{result: &sandbox.ExecuteResult{
+ Stdout: binary,
+ Stderr: "text error",
+ ExitCode: 0,
+ }}
+ tool := NewShellExecTool(executor)
+
+ result, err := tool.Execute(shellExecTestContext(), json.RawMessage(`{"command":"cat image.bin"}`))
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.NotContains(t, result.Output, binary)
+ assert.Contains(t, result.Output, "Binary Output Suppressed")
+ assert.Equal(t, "", result.Data["stdout"])
+ assert.Equal(t, true, result.Data["stdout_binary"])
+ assert.Equal(t, len(binary), result.Data["stdout_bytes"])
+ assert.Equal(t, "text error", result.Data["stderr"])
+}
+
+func TestShellExecDescriptionSupportsGeneralExploration(t *testing.T) {
+ description := NewShellExecTool(&fakeShellExecutor{}).Description()
+
+ for _, command := range []string{"find", "file", "sed", "head", "tail", "cat", "grep", "awk"} {
+ assert.Contains(t, description, command)
+ }
+ assert.Contains(t, description, "Use freely to explore")
+ assert.Contains(t, description, "Binary output is never returned")
+}
+
+func TestShellExecBoundsStdoutStderrErrorAndTotal(t *testing.T) {
+ executor := &fakeShellExecutor{result: &sandbox.ExecuteResult{
+ Stdout: strings.Repeat("o", 100*1024),
+ Stderr: strings.Repeat("s", 40*1024) + "TAIL_ERROR",
+ Error: strings.Repeat("e", 8*1024),
+ }}
+
+ result, err := NewShellExecTool(executor).Execute(
+ shellExecTestContext(),
+ json.RawMessage(`{"command":"noisy","max_output_bytes":999999,"max_stderr_bytes":999999}`),
+ )
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.LessOrEqual(t, len(result.Output), maxShellExecVisibleBytes)
+ assert.LessOrEqual(t, result.Data["stdout_returned_bytes"].(int), maxShellExecOutputBytes)
+ assert.LessOrEqual(t, result.Data["stderr_returned_bytes"].(int), maxShellExecStderrBytes)
+ assert.LessOrEqual(t, result.Data["error_returned_bytes"].(int), maxShellExecErrorBytes)
+ assert.Equal(t, true, result.Data["stdout_truncated"])
+ assert.Equal(t, true, result.Data["stderr_truncated"])
+ assert.Equal(t, true, result.Data["error_truncated"])
+ assert.Contains(t, result.Data["stderr"], "TAIL_ERROR")
+}
+
+func TestShellExecBoundsExecutorErrors(t *testing.T) {
+ executor := &fakeShellExecutor{err: errors.New(strings.Repeat("network failure ", 1024))}
+
+ result, err := NewShellExecTool(executor).Execute(
+ shellExecTestContext(),
+ json.RawMessage(`{"command":"echo hi"}`),
+ )
+
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ assert.LessOrEqual(t, len(result.Error), maxShellExecErrorBytes)
+ assert.Contains(t, result.Error, "truncated")
+}
+
+func TestTruncateShellStreamIncludesMarkerWithinLimit(t *testing.T) {
+ output, truncated := truncateShellStream(strings.Repeat("x", 10000), 100)
+
+ require.True(t, truncated)
+ assert.LessOrEqual(t, len(output), 100)
+ assert.Contains(t, output, "truncated")
+}
diff --git a/internal/agent/tools/skill_execute.go b/internal/agent/tools/skill_execute.go
index be9898610..e9c7b53e7 100644
--- a/internal/agent/tools/skill_execute.go
+++ b/internal/agent/tools/skill_execute.go
@@ -22,6 +22,11 @@ var executeSkillScriptTool = BaseTool{
- Use this tool to run utility scripts bundled with a skill
- Scripts are executed in an isolated sandbox for security
- Only scripts from loaded skills can be executed
+- User-uploaded files are listed in the current ` + "`<sandbox_attachments>`" + `
+ block. Pass their absolute ` + "`/workspace/input/...`" + ` paths through
+ ` + "`args`" + ` when a script accepts an input file.
+- Treat ` + "`/workspace/input`" + ` as read-only. Write generated files only to
+ ` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + ` so they can be collected for download.
## When to Use
- When a skill's instructions reference a utility script (e.g., "Run scripts/analyze_form.py")
@@ -43,7 +48,7 @@ var executeSkillScriptTool = BaseTool{
type ExecuteSkillScriptInput struct {
SkillName string `json:"skill_name" jsonschema:"Name of the skill containing the script"`
ScriptPath string `json:"script_path" jsonschema:"Relative path to the script within the skill directory (e.g. scripts/analyze.py)"`
- Args []string `json:"args,omitempty" jsonschema:"Optional command-line arguments to pass to the script. Note: if using --file flag, you must provide an actual file path that exists in the skill directory. If you have data in memory (not a file), use the 'input' parameter instead."`
+ Args []string `json:"args,omitempty" jsonschema:"Optional command-line arguments. For file flags, pass an absolute path from the current <sandbox_attachments> block (/workspace/input/...). For in-memory data, use input instead."`
Input string `json:"input,omitempty" jsonschema:"Optional input data to pass to the script via stdin. Use this when you have data in memory (e.g. JSON string) that the script should process. This is equivalent to piping data: echo 'data' | python script.py"`
}
diff --git a/internal/application/repository/custom_agent.go b/internal/application/repository/custom_agent.go
index 35bf1112a..eab35e727 100644
--- a/internal/application/repository/custom_agent.go
+++ b/internal/application/repository/custom_agent.go
@@ -73,3 +73,37 @@ func (r *customAgentRepository) CountByModelID(
err := query.Count(&count).Error
return count, err
}
+
+// CountBySandboxConfigID counts agents pointing at a sandbox config.
+//
+// Used only to warn the admin which agents reference a config; never use it to
+// refuse operations. Agent references are permanent state, so blocking on them
+// would make credential rotation impossible.
+func (r *customAgentRepository) CountBySandboxConfigID(
+ ctx context.Context, tenantID uint64, configID string,
+) (int64, error) {
+ var count int64
+ query := r.db.WithContext(ctx).
+ Model(&types.CustomAgent{}).
+ Where("tenant_id = ?", tenantID)
+ query = scopeCustomAgentsBySandboxConfigID(query, configID)
+ err := query.Count(&count).Error
+ return count, err
+}
+
+// ListNamesBySandboxConfigID returns agent names pointing at a sandbox config.
+//
+// Used only to warn the admin which agents reference a config; never use it to
+// refuse operations. Agent references are permanent state, so blocking on them
+// would make credential rotation impossible.
+func (r *customAgentRepository) ListNamesBySandboxConfigID(
+ ctx context.Context, tenantID uint64, configID string,
+) ([]string, error) {
+ var names []string
+ query := r.db.WithContext(ctx).
+ Model(&types.CustomAgent{}).
+ Where("tenant_id = ?", tenantID)
+ query = scopeCustomAgentsBySandboxConfigID(query, configID)
+ err := query.Order("name ASC").Pluck("name", &names).Error
+ return names, err
+}
diff --git a/internal/application/repository/message.go b/internal/application/repository/message.go
index 22d83ac37..d2aa47128 100644
--- a/internal/application/repository/message.go
+++ b/internal/application/repository/message.go
@@ -267,3 +267,67 @@ func (r *messageRepository) UpdateMessageKnowledgeID(
Where("id = ?", messageID).
Update("knowledge_id", knowledgeID).Error
}
+
+// GetSessionArtifacts returns every skill-produced MessageArtifact recorded
+// against any assistant message of the session, in creation order.
+//
+// Projection is scoped to the artifacts JSONB column plus created_at (used
+// to order the flattened output). Assistant messages without artifacts (the
+// common case) contribute an empty slice and cost nothing extra.
+func (r *messageRepository) GetSessionArtifacts(
+ ctx context.Context, sessionID string,
+) (types.MessageArtifacts, error) {
+ if sessionID == "" {
+ return nil, nil
+ }
+ var rows []struct {
+ Artifacts types.MessageArtifacts `gorm:"column:artifacts"`
+ CreatedAt time.Time `gorm:"column:created_at"`
+ }
+ if err := r.db.WithContext(ctx).
+ Model(&types.Message{}).
+ Select("artifacts", "created_at").
+ Where("session_id = ? AND deleted_at IS NULL", sessionID).
+ Order("created_at ASC").
+ Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ if len(rows) == 0 {
+ return types.MessageArtifacts{}, nil
+ }
+ result := make(types.MessageArtifacts, 0, len(rows))
+ for _, row := range rows {
+ if len(row.Artifacts) == 0 {
+ continue
+ }
+ result = append(result, row.Artifacts...)
+ }
+ return result, nil
+}
+
+// GetSessionAttachments returns every user-uploaded attachment in creation
+// order while projecting only the attachments JSON column.
+func (r *messageRepository) GetSessionAttachments(
+ ctx context.Context, sessionID string,
+) (types.MessageAttachments, error) {
+ if sessionID == "" {
+ return nil, nil
+ }
+ var rows []struct {
+ Attachments types.MessageAttachments `gorm:"column:attachments"`
+ CreatedAt time.Time `gorm:"column:created_at"`
+ }
+ if err := r.db.WithContext(ctx).
+ Model(&types.Message{}).
+ Select("attachments", "created_at").
+ Where("session_id = ? AND deleted_at IS NULL", sessionID).
+ Order("created_at ASC").
+ Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ result := make(types.MessageAttachments, 0, len(rows))
+ for _, row := range rows {
+ result = append(result, row.Attachments...)
+ }
+ return result, nil
+}
diff --git a/internal/application/repository/model_usage.go b/internal/application/repository/model_usage.go
index f8336870a..686b271ef 100644
--- a/internal/application/repository/model_usage.go
+++ b/internal/application/repository/model_usage.go
@@ -49,3 +49,10 @@ func scopeCustomAgentsByModelID(db *gorm.DB, modelID string) *gorm.DB {
modelID, modelID, modelID, modelID, modelID, modelID,
)
}
+
+func scopeCustomAgentsBySandboxConfigID(db *gorm.DB, configID string) *gorm.DB {
+ if db.Dialector.Name() == "postgres" {
+ return db.Where("config->>'sandbox_config_id' = ?", configID)
+ }
+ return db.Where("json_extract(config, '$.sandbox_config_id') = ?", configID)
+}
diff --git a/internal/application/repository/model_usage_test.go b/internal/application/repository/model_usage_test.go
index a8358fef3..f8777a170 100644
--- a/internal/application/repository/model_usage_test.go
+++ b/internal/application/repository/model_usage_test.go
@@ -111,3 +111,28 @@ func TestCountByModelID_CustomAgent(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, int64(1), count)
}
+
+func TestCustomAgentSandboxConfigReferences(t *testing.T) {
+ ctx := context.Background()
+ db := setupModelUsageTestDB(t)
+ repo := NewCustomAgentRepository(db)
+ configID := "sandbox-cfg-1"
+
+ require.NoError(t, db.Exec(
+ `INSERT INTO custom_agents (id, name, tenant_id, config) VALUES
+ (?, ?, ?, ?),
+ (?, ?, ?, ?),
+ (?, ?, ?, ?)`,
+ uuid.New().String(), "analysis-agent", 1, `{"sandbox_config_id":"sandbox-cfg-1"}`,
+ uuid.New().String(), "other-agent", 1, `{"sandbox_config_id":"sandbox-cfg-2"}`,
+ uuid.New().String(), "other-tenant-agent", 2, `{"sandbox_config_id":"sandbox-cfg-1"}`,
+ ).Error)
+
+ count, err := repo.CountBySandboxConfigID(ctx, 1, configID)
+ require.NoError(t, err)
+ assert.Equal(t, int64(1), count)
+
+ names, err := repo.ListNamesBySandboxConfigID(ctx, 1, configID)
+ require.NoError(t, err)
+ assert.Equal(t, []string{"analysis-agent"}, names)
+}
diff --git a/internal/application/repository/tenant_sandbox_config.go b/internal/application/repository/tenant_sandbox_config.go
new file mode 100644
index 000000000..dbb0dbe50
--- /dev/null
+++ b/internal/application/repository/tenant_sandbox_config.go
@@ -0,0 +1,135 @@
+// Package repository persists sandbox backend configuration.
+//
+// Every read and write is scoped by tenant_id. Sandbox configs carry provider
+// credentials, so a query that forgets the scope is a cross-workspace credential
+// leak, not merely a bug.
+package repository
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "gorm.io/gorm"
+)
+
+// TenantSandboxConfigRepository persists named sandbox backend configs.
+type TenantSandboxConfigRepository interface {
+ Create(ctx context.Context, e *types.TenantSandboxConfigEntity) error
+ GetByID(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
+ ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantSandboxConfigEntity, error)
+ Update(ctx context.Context, e *types.TenantSandboxConfigEntity) error
+ SoftDelete(ctx context.Context, tenantID uint64, id string) error
+ SetCordon(ctx context.Context, tenantID uint64, id string, at time.Time) error
+ ClearCordon(ctx context.Context, tenantID uint64, id string) error
+}
+
+type tenantSandboxConfigRepository struct {
+ db *gorm.DB
+}
+
+// NewTenantSandboxConfigRepository returns a GORM-backed implementation.
+func NewTenantSandboxConfigRepository(db *gorm.DB) TenantSandboxConfigRepository {
+ return &tenantSandboxConfigRepository{db: db}
+}
+
+func (r *tenantSandboxConfigRepository) Create(
+ ctx context.Context, e *types.TenantSandboxConfigEntity,
+) error {
+ return r.db.WithContext(ctx).Create(e).Error
+}
+
+// GetByID returns nil (no error) when the config does not exist or belongs to
+// another workspace, so callers can render a 404 without inspecting errors.
+func (r *tenantSandboxConfigRepository) GetByID(
+ ctx context.Context, tenantID uint64, id string,
+) (*types.TenantSandboxConfigEntity, error) {
+ var e types.TenantSandboxConfigEntity
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ? AND id = ?", tenantID, id).
+ First(&e).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &e, nil
+}
+
+func (r *tenantSandboxConfigRepository) ListByTenant(
+ ctx context.Context, tenantID uint64,
+) ([]*types.TenantSandboxConfigEntity, error) {
+ var list []*types.TenantSandboxConfigEntity
+ err := r.db.WithContext(ctx).
+ Where("tenant_id = ?", tenantID).
+ Order("created_at ASC").
+ Find(&list).Error
+ if err != nil {
+ return nil, err
+ }
+ return list, nil
+}
+
+// Update writes the mutable columns. Select is explicit so a zero-valued
+// CordonedAt on the passed entity cannot silently release someone else's lease.
+func (r *tenantSandboxConfigRepository) Update(
+ ctx context.Context, e *types.TenantSandboxConfigEntity,
+) error {
+ return r.db.WithContext(ctx).
+ Model(&types.TenantSandboxConfigEntity{}).
+ Where("tenant_id = ? AND id = ?", e.TenantID, e.ID).
+ Select("name", "description", "sandbox_type", "config", "updated_at").
+ Updates(map[string]any{
+ "name": e.Name,
+ "description": e.Description,
+ "sandbox_type": e.SandboxType,
+ "config": e.Config,
+ "updated_at": time.Now(),
+ }).Error
+}
+
+func (r *tenantSandboxConfigRepository) SoftDelete(
+ ctx context.Context, tenantID uint64, id string,
+) error {
+ return r.db.WithContext(ctx).
+ Where("tenant_id = ? AND id = ?", tenantID, id).
+ Delete(&types.TenantSandboxConfigEntity{}).Error
+}
+
+// ErrSandboxConfigCordoned is returned by SetCordon when another request
+// already holds a fresh cordon lease on the same config row.
+var ErrSandboxConfigCordoned = errors.New("sandbox config is being modified by another request")
+
+// SetCordon must be committed before the caller lists provider sandboxes:
+// resolution paths only stop creating sandboxes once they can see it.
+//
+// The update is a conditional CAS: it refuses to overwrite a cordon that is
+// still within the lease window, so two concurrent identity-change requests
+// cannot race past each other.
+func (r *tenantSandboxConfigRepository) SetCordon(
+ ctx context.Context, tenantID uint64, id string, at time.Time,
+) error {
+ result := r.db.WithContext(ctx).
+ Model(&types.TenantSandboxConfigEntity{}).
+ Where("tenant_id = ? AND id = ?", tenantID, id).
+ Where("cordoned_at IS NULL OR cordoned_at < ?", at.Add(-types.SandboxCordonLease)).
+ Update("cordoned_at", at)
+ if result.Error != nil {
+ return result.Error
+ }
+ if result.RowsAffected == 0 {
+ return ErrSandboxConfigCordoned
+ }
+ return nil
+}
+
+func (r *tenantSandboxConfigRepository) ClearCordon(
+ ctx context.Context, tenantID uint64, id string,
+) error {
+ return r.db.WithContext(ctx).
+ Model(&types.TenantSandboxConfigEntity{}).
+ Where("tenant_id = ? AND id = ?", tenantID, id).
+ Update("cordoned_at", nil).Error
+}
diff --git a/internal/application/repository/tenant_sandbox_config_test.go b/internal/application/repository/tenant_sandbox_config_test.go
new file mode 100644
index 000000000..00e89427c
--- /dev/null
+++ b/internal/application/repository/tenant_sandbox_config_test.go
@@ -0,0 +1,118 @@
+package repository
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+)
+
+func newSandboxConfigTestRepo(t *testing.T) (TenantSandboxConfigRepository, *gorm.DB) {
+ t.Helper()
+
+ db, err := gorm.Open(sqlite.Open("file:"+uuid.NewString()+"?mode=memory&cache=shared"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(&types.TenantSandboxConfigEntity{}))
+ // AutoMigrate cannot express the partial unique index, so add it here to
+ // match the production migration.
+ require.NoError(t, db.Exec(
+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_sandbox_configs_tenant_name
+ ON tenant_sandbox_configs (tenant_id, name) WHERE deleted_at IS NULL`).Error)
+ return NewTenantSandboxConfigRepository(db), db
+}
+
+func TestSandboxConfigRepoIsolatesTenants(t *testing.T) {
+ repo, _ := newSandboxConfigTestRepo(t)
+ ctx := context.Background()
+
+ require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 1,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
+ }))
+ require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
+ ID: "cfg-b",
+ TenantID: 2,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
+ }))
+
+ // Same name in a different workspace is fine; cross-tenant reads are not.
+ got, err := repo.GetByID(ctx, 1, "cfg-b")
+ require.NoError(t, err)
+ require.Nil(t, got, "must not read another workspace's config")
+
+ list, err := repo.ListByTenant(ctx, 1)
+ require.NoError(t, err)
+ require.Len(t, list, 1)
+ require.Equal(t, "cfg-a", list[0].ID)
+}
+
+func TestSandboxConfigRepoRejectsDuplicateNameInTenant(t *testing.T) {
+ repo, _ := newSandboxConfigTestRepo(t)
+ ctx := context.Background()
+
+ base := func(id string) *types.TenantSandboxConfigEntity {
+ return &types.TenantSandboxConfigEntity{
+ ID: id,
+ TenantID: 1,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
+ }
+ }
+ require.NoError(t, repo.Create(ctx, base("cfg-1")))
+ require.Error(t, repo.Create(ctx, base("cfg-2")))
+}
+
+func TestSandboxConfigRepoSoftDeleteHidesRow(t *testing.T) {
+ repo, _ := newSandboxConfigTestRepo(t)
+ ctx := context.Background()
+
+ require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 1,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
+ }))
+ require.NoError(t, repo.SoftDelete(ctx, 1, "cfg-a"))
+
+ got, err := repo.GetByID(ctx, 1, "cfg-a")
+ require.NoError(t, err)
+ require.Nil(t, got)
+}
+
+func TestSandboxConfigRepoCordonRoundTrip(t *testing.T) {
+ repo, _ := newSandboxConfigTestRepo(t)
+ ctx := context.Background()
+
+ require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 1,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
+ }))
+
+ at := time.Now().UTC().Truncate(time.Second)
+ require.NoError(t, repo.SetCordon(ctx, 1, "cfg-a", at))
+
+ got, err := repo.GetByID(ctx, 1, "cfg-a")
+ require.NoError(t, err)
+ require.NotNil(t, got.CordonedAt)
+ require.True(t, got.IsCordoned(at.Add(time.Second), types.SandboxCordonLease))
+
+ require.NoError(t, repo.ClearCordon(ctx, 1, "cfg-a"))
+ got, err = repo.GetByID(ctx, 1, "cfg-a")
+ require.NoError(t, err)
+ require.Nil(t, got.CordonedAt)
+}
diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go
index 171420eaa..b75fc1ee2 100644
--- a/internal/application/service/agent_service.go
+++ b/internal/application/service/agent_service.go
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"strconv"
+ "strings"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/approval"
@@ -103,6 +104,10 @@ type agentService struct {
tenantService interfaces.TenantService
storageResolver interfaces.StorageBackendResolver
toolApprovalGate approval.MCPApproval
+ sandboxMgr sandbox.Manager
+ sandboxResolver sandbox.TenantSandboxResolver
+ sandboxPinner *SessionSandboxPinner
+ sandboxPolicy WorkspaceSandboxPolicy
}
// NewAgentService creates a new agent service
@@ -124,6 +129,10 @@ func NewAgentService(
tenantService interfaces.TenantService,
storageResolver interfaces.StorageBackendResolver,
toolApprovalGate approval.MCPApproval,
+ sandboxMgr sandbox.Manager,
+ sandboxResolver sandbox.TenantSandboxResolver,
+ sandboxPinner *SessionSandboxPinner,
+ sandboxPolicy WorkspaceSandboxPolicy,
) interfaces.AgentService {
return &agentService{
cfg: cfg,
@@ -143,6 +152,10 @@ func NewAgentService(
tenantService: tenantService,
storageResolver: storageResolver,
toolApprovalGate: toolApprovalGate,
+ sandboxMgr: sandboxMgr,
+ sandboxResolver: sandboxResolver,
+ sandboxPinner: sandboxPinner,
+ sandboxPolicy: sandboxPolicy,
}
}
@@ -217,7 +230,7 @@ func (s *agentService) CreateAgentEngine(
// Initialize skills manager if skills are enabled
if config.SkillsEnabled && len(config.SkillDirs) > 0 {
- skillsManager, err := s.initializeSkillsManager(ctx, config, toolRegistry)
+ skillsManager, err := s.initializeSkillsManager(ctx, sessionID, config, toolRegistry)
if err != nil {
logger.Warnf(ctx, "Failed to initialize skills manager: %v", err)
} else if skillsManager != nil {
@@ -336,52 +349,44 @@ func (s *agentService) resolveKBAndDocInfos(
return kbInfos, selectedDocs
}
-// initializeSkillsManager creates and initializes the skills manager
+// initializeSkillsManager creates and initializes the skills manager.
+//
+// The sandbox manager is resolved per workspace: backends differ in
+// capability (E2B exposes a session file store, local does not), so tool
+// registration below must inspect this workspace's real manager rather than a
+// process-wide singleton. Workspaces without their own sandbox configuration
+// resolve to the injected default.
func (s *agentService) initializeSkillsManager(
ctx context.Context,
+ sessionID string,
config *types.AgentConfig,
toolRegistry *tools.ToolRegistry,
) (*skills.Manager, error) {
- // Initialize sandbox manager based on environment variables
- // WEKNORA_SANDBOX_MODE: "docker", "local", "disabled" (default: "disabled")
- // WEKNORA_SANDBOX_TIMEOUT: timeout in seconds (default: 60)
- // WEKNORA_SANDBOX_DOCKER_IMAGE: custom Docker image (default: wechatopenai/weknora-sandbox:latest)
- var sandboxMgr sandbox.Manager
- var err error
+ tenantID, _ := types.TenantIDFromContext(ctx)
+ configID, err := sandboxConfigForExecution(ctx, s.sandboxPinner, sessionID, config.SandboxConfigID)
+ if err != nil {
+ return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)
+ }
+ sandboxMgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy)
+ if err != nil {
+ return nil, err
+ }
+ if sandboxMgr == nil {
+ sandboxMgr = sandbox.NewDisabledManager()
+ }
- sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")
+ sandboxMode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
if sandboxMode == "" {
sandboxMode = "disabled"
}
- dockerImage := os.Getenv("WEKNORA_SANDBOX_DOCKER_IMAGE")
- if dockerImage == "" {
- dockerImage = sandbox.DefaultDockerImage
- }
- sandboxTimeoutStr := os.Getenv("WEKNORA_SANDBOX_TIMEOUT")
sandboxTimeout := 60
- if sandboxTimeoutStr != "" {
- if v, err := strconv.Atoi(sandboxTimeoutStr); err == nil && v > 0 {
- sandboxTimeout = v
+ if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ sandboxTimeout = n
}
}
-
- switch sandboxMode {
- case "docker":
- sandboxMgr, err = sandbox.NewManagerFromType("docker", true, dockerImage) // Enable fallback to local
- if err != nil {
- logger.Warnf(ctx, "Failed to initialize Docker sandbox, falling back to disabled: %v", err)
- sandboxMgr = sandbox.NewDisabledManager()
- }
- case "local":
- sandboxMgr, err = sandbox.NewManagerFromType("local", false, "")
- if err != nil {
- logger.Warnf(ctx, "Failed to initialize local sandbox: %v", err)
- sandboxMgr = sandbox.NewDisabledManager()
- }
- default:
- sandboxMgr = sandbox.NewDisabledManager()
- }
- logger.Infof(ctx, "Sandbox configured: mode=%s, timeout=%ds, image=%s", sandboxMode, sandboxTimeout, dockerImage)
+ logger.Infof(ctx, "Sandbox in use: mode=%s type=%s timeout=%ds",
+ sandboxMode, sandboxMgr.GetType(), sandboxTimeout)
// Create skills manager
skillsConfig := &skills.ManagerConfig{
@@ -402,10 +407,35 @@ func (s *agentService) initializeSkillsManager(
toolRegistry.RegisterTool(readSkillTool)
logger.Infof(ctx, "Registered read_skill tool")
- if sandboxMode != "disabled" {
+ if sandboxMgr.GetType() != sandbox.SandboxTypeDisabled {
executeSkillTool := tools.NewExecuteSkillScriptTool(skillsManager)
toolRegistry.RegisterTool(executeSkillTool)
logger.Infof(ctx, "Registered execute_skill_script tool")
+
+ // list_sandbox_files / read_sandbox_file expose per-session
+ // filesystem inspection. Registration is gated on the sandbox
+ // manager advertising a SessionFileStore capability — providers
+ // that fell back to a stateless local sandbox return nil so we
+ // never surface tenant-isolated tools that would run on the
+ // WeKnora host.
+ if store := sessionSandboxFileStore(sandboxMgr); store != nil {
+ toolRegistry.RegisterTool(tools.NewListSandboxFilesTool(store))
+ toolRegistry.RegisterTool(tools.NewReadSandboxFileTool(store))
+ logger.Infof(ctx, "Registered list_sandbox_files and read_sandbox_file tools")
+ } else {
+ logger.Infof(ctx, "Sandbox backend does not advertise session filesystem capability; list_sandbox_files/read_sandbox_file not registered")
+ }
+
+ // shell_exec is a remote-only capability. SessionCapabilityProvider
+ // yields nil for stateless backends and for a SessionBoundManager
+ // that fell back to LocalSandbox, so the same check works for
+ // every provider (Cube, E2B, future backends).
+ if executor := sessionSandboxShellExecutor(sandboxMgr); executor != nil {
+ toolRegistry.RegisterTool(tools.NewShellExecTool(executor))
+ logger.Infof(ctx, "Registered shell_exec tool")
+ } else {
+ logger.Infof(ctx, "Sandbox backend does not advertise remote shell capability; shell_exec not registered")
+ }
}
return skillsManager, nil
diff --git a/internal/application/service/agent_service_shell_test.go b/internal/application/service/agent_service_shell_test.go
new file mode 100644
index 000000000..5e09bf0d5
--- /dev/null
+++ b/internal/application/service/agent_service_shell_test.go
@@ -0,0 +1,73 @@
+package service
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/stretchr/testify/assert"
+)
+
+// capableManager is a test double that lets each case declare which
+// session-scoped capabilities the sandbox manager currently advertises.
+// It mirrors the real SessionCapabilityProvider contract SessionBoundManager
+// implements, without pulling in the full manager wiring.
+type capableManager struct {
+ typ sandbox.SandboxType
+ shell sandbox.SessionShellExecutor
+ files sandbox.SessionFileStore
+}
+
+func (m *capableManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
+ return &sandbox.ExecuteResult{}, nil
+}
+func (m *capableManager) Cleanup(context.Context) error { return nil }
+func (m *capableManager) GetSandbox() sandbox.Sandbox { return nil }
+func (m *capableManager) GetType() sandbox.SandboxType { return m.typ }
+func (m *capableManager) SessionShellExecutor() sandbox.SessionShellExecutor {
+ return m.shell
+}
+func (m *capableManager) SessionFileStore() sandbox.SessionFileStore {
+ return m.files
+}
+
+// stubShellExecutor records ExecShellCommand calls so a test can assert the
+// registered tool actually dispatches through it.
+type stubShellExecutor struct{ called bool }
+
+func (s *stubShellExecutor) ExecShellCommand(
+ context.Context, string, string, string, time.Duration, map[string]string,
+) (*sandbox.ExecuteResult, error) {
+ s.called = true
+ return &sandbox.ExecuteResult{}, nil
+}
+
+func TestSessionSandboxShellExecutorReturnsNilWithoutCapability(t *testing.T) {
+ // Managers that don't implement SessionCapabilityProvider (Local /
+ // Docker / Disabled DefaultManager) must never surface shell_exec.
+ nonCapable := &capableManager{typ: sandbox.SandboxTypeLocal}
+ assert.Nil(t, sessionSandboxShellExecutor(nonCapable))
+ assert.Nil(t, sessionSandboxFileStore(nonCapable))
+ assert.Nil(t, sessionSandboxShellExecutor(nil))
+}
+
+func TestSessionSandboxShellExecutorReturnsNilWhenProviderRefuses(t *testing.T) {
+ // A provider that advertises capabilities but is currently unable to
+ // honour them (e.g. SessionBoundManager after Local fallback) returns
+ // nil from the accessor. The tool layer must respect that.
+ m := &capableManager{typ: sandbox.SandboxTypeCube}
+ assert.Nil(t, sessionSandboxShellExecutor(m))
+ assert.Nil(t, sessionSandboxFileStore(m))
+}
+
+func TestSessionSandboxShellExecutorReturnsCapability(t *testing.T) {
+ exec := &stubShellExecutor{}
+ m := &capableManager{typ: sandbox.SandboxTypeCube, shell: exec}
+ got := sessionSandboxShellExecutor(m)
+ assert.NotNil(t, got)
+ if _, err := got.ExecShellCommand(context.Background(), "sid", "echo", "", 0, nil); err != nil {
+ t.Fatalf("dispatch through capability: %v", err)
+ }
+ assert.True(t, exec.called)
+}
diff --git a/internal/application/service/artifact_collector.go b/internal/application/service/artifact_collector.go
new file mode 100644
index 000000000..30c21a7a4
--- /dev/null
+++ b/internal/application/service/artifact_collector.go
@@ -0,0 +1,439 @@
+// Package service - artifact collector.
+//
+// ArtifactCollector drains a session sandbox's output directory into the
+// tenant file service after a skill turn finishes. It is intentionally kept
+// stateless and testable: a narrow SandboxArtifactSource interface abstracts
+// the sandbox side so unit tests can stub in a fake filesystem, and the
+// file service is passed in so blobs land in the same storage backend the
+// tenant already uses for uploaded attachments.
+//
+// Contract:
+// - Never delete files from the sandbox — skills can share files across
+// turns; deletion would break that (spec §2, "不清空输出目录").
+// - Never lazy-create a sandbox: the collector reads from an already-live
+// sandbox and returns an empty slice when none exists.
+// - Best-effort: individual errors are logged and skipped, never returned,
+// so a stray unreadable file cannot block the assistant reply.
+// - De-duplication by (SourcePath, ModTime): if a prior message in the
+// same session already recorded the same (path, mtime), skip it.
+package service
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/google/uuid"
+)
+
+// SandboxArtifactSource is the narrow subset of sandbox behaviour the
+// collector needs. SessionBoundManager satisfies it in production; tests
+// use a fake to drive the diff logic without a real sandbox.
+type SandboxArtifactSource interface {
+ ListSessionFiles(ctx context.Context, sessionID, dir string) ([]sandbox.RemoteDirEntry, error)
+ ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
+}
+
+// SessionArtifactStore is the minimal repository surface the collector needs
+// to compute the "already recorded" set for a session. In production it is
+// backed by the message repository; in tests it is stubbed with an in-memory
+// map so the collector can be exercised without a database.
+type SessionArtifactStore interface {
+ // KnownArtifacts returns every (SourcePath, ModTime) pair already
+ // attached to any prior message of the session. The returned set is
+ // unordered and safe to mutate by the caller.
+ KnownArtifacts(ctx context.Context, sessionID string) ([]types.MessageArtifact, error)
+}
+
+// ArtifactCollectorConfig bounds the collector's I/O and storage footprint.
+// All fields have safe zero-value defaults applied by newBoundedConfig.
+type ArtifactCollectorConfig struct {
+ // OutputDir is the absolute path inside the sandbox to scan. Empty
+ // falls back to skills.ArtifactOutputDir() at call time.
+ OutputDir string
+
+ // MaxFileBytes is the largest single file that will be persisted.
+ // Files larger than this are logged and skipped so a runaway skill
+ // cannot exhaust the WeKnora process's memory.
+ MaxFileBytes int64
+}
+
+// defaultMaxArtifactFileBytes caps a single artifact at 50 MiB. Larger files
+// stream from the sandbox in a single ReadFile call today, so we cap here to
+// protect the process from OOM. The cap can be raised via config once the
+// sandbox client learns to stream to disk.
+const defaultMaxArtifactFileBytes int64 = 50 * 1024 * 1024
+
+// Resource binding coordinates for collected artifacts. The owner is the
+// assistant message that produced the file (mirrors how knowledge uploads
+// bind to "knowledge" and chat attachments bind to "temporary_document"),
+// so the resource registry can enumerate / garbage-collect artifacts by
+// their owning message instead of only via the messages.artifacts JSONB.
+const (
+ artifactBindingOwnerType = "message"
+ artifactBindingRelation = "artifact"
+)
+
+// ArtifactCollector implements the "drain sandbox artifacts on turn
+// completion" step described in
+// docs/superpowers/specs/2026-07-10-skill-artifact-download-design.md §4.
+type ArtifactCollector struct {
+ source SandboxArtifactSource
+ fileService interfaces.FileService
+ store SessionArtifactStore
+ // catalog binds each persisted artifact resource to its owning message.
+ // Optional: nil when the deployment runs without a resource registry, in
+ // which case artifacts are still saved and downloadable — they just are
+ // not tracked as owned resources.
+ catalog interfaces.ResourceCatalog
+ config ArtifactCollectorConfig
+ // resolver lets Collect use the workspace's own sandbox backend. Optional:
+ // nil keeps the process-wide source for every workspace.
+ resolver sandbox.TenantSandboxResolver
+ pinner *SessionSandboxPinner
+ // fallbackMgr is the deployment-wide SessionBoundManager. Sentinel pins
+ // ("-") resolve to it rather than a per-config manager.
+ fallbackMgr sandbox.Manager
+}
+
+// NewArtifactCollector wires up an ArtifactCollector. Callers keep a single
+// instance per process; the collector holds no per-turn state. catalog may be
+// nil (resource registry disabled); binding is then skipped.
+func NewArtifactCollector(
+ source SandboxArtifactSource,
+ fileService interfaces.FileService,
+ store SessionArtifactStore,
+ catalog interfaces.ResourceCatalog,
+ config ArtifactCollectorConfig,
+) *ArtifactCollector {
+ return &ArtifactCollector{
+ source: source,
+ fileService: fileService,
+ store: store,
+ catalog: catalog,
+ config: newBoundedConfig(config),
+ }
+}
+
+// NewArtifactCollectorFromSandboxManager is the DI-friendly constructor
+// that promotes a sandbox.Manager to SandboxArtifactSource only when the
+// underlying implementation actually supports per-session file inspection
+// (currently *sandbox.SessionBoundManager). For any other backend the
+// returned *ArtifactCollector is nil, which the AgentStreamHandler treats
+// as "no artifacts to attach" — matching the graceful-degradation contract
+// documented in the design spec.
+// The resolver is consulted per turn so a workspace whose own backend supports
+// artifacts still gets them even when the process-wide default does not. The
+// collector is therefore built whenever either side could supply a source, and
+// Collect degrades to "nothing to attach" when neither does.
+func NewArtifactCollectorFromSandboxManager(
+ sandboxMgr sandbox.Manager,
+ sandboxResolver sandbox.TenantSandboxResolver,
+ pinner *SessionSandboxPinner,
+ fileService interfaces.FileService,
+ repo interfaces.MessageRepository,
+ catalog interfaces.ResourceCatalog,
+) *ArtifactCollector {
+ if fileService == nil {
+ return nil
+ }
+ source, _ := sandboxMgr.(SandboxArtifactSource)
+ if source == nil && sandboxResolver == nil {
+ return nil
+ }
+ collector := NewArtifactCollector(
+ source,
+ fileService,
+ NewMessageRepoArtifactStore(repo),
+ catalog,
+ ArtifactCollectorConfig{},
+ )
+ collector.resolver = sandboxResolver
+ collector.pinner = pinner
+ collector.fallbackMgr = sandboxMgr
+ return collector
+}
+
+// sessionSource returns the artifact source for the sandbox pinned to
+// sessionID, never the one the agent points at today: the sandbox being drained
+// was created earlier and may live on a config the agent no longer selects.
+//
+// Returns nil when the session has no pin, which Collect treats as "nothing to
+// attach".
+func (c *ArtifactCollector) sessionSource(ctx context.Context, sessionID string) SandboxArtifactSource {
+ if c.resolver == nil {
+ return c.source
+ }
+ tenantID, _ := types.TenantIDFromContext(ctx)
+ configID, err := sandboxConfigForExistingSandbox(ctx, c.pinner, sessionID)
+ if err != nil {
+ logger.Warnf(ctx, "[ArtifactCollector] read sandbox pin failed: %v", err)
+ return nil
+ }
+ if configID == "" {
+ return nil
+ }
+ mgr, err := resolveTenantSandboxForConfig(
+ ctx, c.resolver, c.fallbackMgr, tenantID, configID, nil,
+ )
+ if err != nil {
+ // Refusing to read is the safe failure: substituting another backend
+ // would look in the wrong provider account and report "no artifacts".
+ logger.Warnf(ctx, "[ArtifactCollector] resolve sandbox failed: %v", err)
+ return nil
+ }
+ if mgr == nil {
+ // The pin names the deployment-wide default, which has no per-config
+ // manager of its own; the injected process-wide source IS that backend.
+ return c.source
+ }
+ if source, ok := mgr.(SandboxArtifactSource); ok {
+ return source
+ }
+ if configID == types.SandboxConfigIDGlobalDefault {
+ return c.source
+ }
+ return nil
+}
+
+// newBoundedConfig fills in defaults so callers can pass a zero
+// ArtifactCollectorConfig without hitting empty-value edge cases.
+func newBoundedConfig(cfg ArtifactCollectorConfig) ArtifactCollectorConfig {
+ if cfg.MaxFileBytes <= 0 {
+ cfg.MaxFileBytes = defaultMaxArtifactFileBytes
+ }
+ return cfg
+}
+
+// Collect scans the session sandbox's output directory and persists any
+// newly-created or newly-modified files to the tenant file service.
+//
+// The returned slice contains one MessageArtifact per persisted file. When
+// no sandbox is bound to the session, or when the source is nil (skill
+// backend disabled), Collect returns nil, nil — the caller is expected to
+// treat both cases as "nothing to attach" and NOT set message.Artifacts.
+//
+// Errors returned by Collect are limited to internal invariants (nil
+// dependencies). Per-file errors (unreadable, too-large, upload failure)
+// are logged and skipped so a single misbehaving artifact never breaks the
+// turn.
+func (c *ArtifactCollector) Collect(
+ ctx context.Context,
+ sessionID string,
+ messageID string,
+ tenantID uint64,
+ outputDir string,
+) (types.MessageArtifacts, error) {
+ if c == nil || c.fileService == nil {
+ logger.Infof(ctx, "[ArtifactCollector] skipped: collector or dependencies nil (session=%s)", sessionID)
+ return nil, nil
+ }
+ source := c.sessionSource(ctx, sessionID)
+ if source == nil {
+ logger.Infof(ctx,
+ "[ArtifactCollector] skipped: sandbox backend has no session filesystem (session=%s)",
+ sessionID)
+ return nil, nil
+ }
+ if sessionID == "" {
+ logger.Infof(ctx, "[ArtifactCollector] skipped: empty sessionID")
+ return nil, nil
+ }
+ if outputDir == "" {
+ outputDir = c.config.OutputDir
+ }
+ if outputDir == "" {
+ // Callers should have resolved this via skills.ArtifactOutputDir
+ // but we guard here anyway to keep Collect self-contained.
+ logger.Infof(ctx, "[ArtifactCollector] skipped: empty outputDir (session=%s)", sessionID)
+ return nil, nil
+ }
+
+ logger.Infof(ctx, "[ArtifactCollector] begin session=%s dir=%s", sessionID, outputDir)
+
+ entries, err := source.ListSessionFiles(ctx, sessionID, outputDir)
+ if err != nil {
+ logger.Warnf(ctx, "[ArtifactCollector] list sandbox files failed: session=%s dir=%s err=%v",
+ sessionID, outputDir, err)
+ return nil, nil
+ }
+ if len(entries) == 0 {
+ // The most common cause of "download button never appears" is
+ // exactly this branch: either the sandbox was already reaped or
+ // the skill wrote to a different directory. Logging the exact
+ // (session, dir) pair makes it a 30-second grep to confirm.
+ logger.Infof(ctx, "[ArtifactCollector] no entries under %s (session=%s) — sandbox reaped or skill wrote elsewhere",
+ outputDir, sessionID)
+ return nil, nil
+ }
+ logger.Infof(ctx, "[ArtifactCollector] listed %d entries under %s (session=%s)", len(entries), outputDir, sessionID)
+
+ // Build a "already recorded" set so we don't double-attach the same
+ // file when several turns share the sandbox. Errors here degrade to an
+ // empty set: attaching duplicates is a soft failure, aborting is not.
+ known := c.loadKnownSet(ctx, sessionID)
+ if len(known) > 0 {
+ logger.Infof(ctx, "[ArtifactCollector] known set size=%d (session=%s)", len(known), sessionID)
+ }
+
+ artifacts := make(types.MessageArtifacts, 0, len(entries))
+ for _, entry := range entries {
+ art, ok := c.maybePersist(ctx, source, sessionID, messageID, tenantID, entry, known)
+ if !ok {
+ continue
+ }
+ artifacts = append(artifacts, art)
+ // Adding to the known set inside the loop protects us against the
+ // pathological case where ListSessionFiles returns the same path
+ // twice (envd hasn't been observed to do so, but future-proofing
+ // the loop is cheap).
+ known[artifactKey(art.SourcePath, art.ModTime)] = struct{}{}
+ }
+ logger.Infof(ctx, "[ArtifactCollector] done session=%s listed=%d attached=%d",
+ sessionID, len(entries), len(artifacts))
+ return artifacts, nil
+}
+
+// loadKnownSet returns the (source_path, mod_time) tuples already recorded
+// against the session. Empty on error so the caller can proceed.
+func (c *ArtifactCollector) loadKnownSet(ctx context.Context, sessionID string) map[string]struct{} {
+ set := map[string]struct{}{}
+ if c.store == nil {
+ return set
+ }
+ prev, err := c.store.KnownArtifacts(ctx, sessionID)
+ if err != nil {
+ logger.Warnf(ctx, "[ArtifactCollector] load previous artifacts failed: session=%s err=%v",
+ sessionID, err)
+ return set
+ }
+ for _, p := range prev {
+ set[artifactKey(p.SourcePath, p.ModTime)] = struct{}{}
+ }
+ return set
+}
+
+// maybePersist runs the per-file pipeline (filter → download → upload →
+// build metadata). Returns ok=false when the entry was skipped for any
+// reason (already known, too large, upload failed). All skip reasons are
+// logged so operators can diagnose empty artifact panels.
+func (c *ArtifactCollector) maybePersist(
+ ctx context.Context,
+ source SandboxArtifactSource,
+ sessionID string,
+ messageID string,
+ tenantID uint64,
+ entry sandbox.RemoteDirEntry,
+ known map[string]struct{},
+) (types.MessageArtifact, bool) {
+ // Only files reach here (SessionBoundManager.listFilesRecursive filters
+ // directories), but we defensively double-check so callers passing an
+ // alternate SandboxArtifactSource don't break the assumption.
+ if entry.Type != sandbox.RemoteEntryFile {
+ return types.MessageArtifact{}, false
+ }
+ if entry.Path == "" || entry.Name == "" {
+ return types.MessageArtifact{}, false
+ }
+ if entry.Size > c.config.MaxFileBytes {
+ logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact: session=%s path=%s size=%d limit=%d",
+ sessionID, entry.Path, entry.Size, c.config.MaxFileBytes)
+ return types.MessageArtifact{}, false
+ }
+
+ modTime := entry.ModTime
+ key := artifactKey(entry.Path, modTime)
+ if _, seen := known[key]; seen {
+ return types.MessageArtifact{}, false
+ }
+
+ data, err := source.ReadSessionFile(ctx, sessionID, entry.Path)
+ if err != nil {
+ logger.Warnf(ctx, "[ArtifactCollector] read artifact failed: session=%s path=%s err=%v",
+ sessionID, entry.Path, err)
+ return types.MessageArtifact{}, false
+ }
+ // A second guard: envd may report a stale size while the file is being
+ // re-written; enforce the cap against the actual byte count too.
+ if int64(len(data)) > c.config.MaxFileBytes {
+ logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact after read: session=%s path=%s size=%d limit=%d",
+ sessionID, entry.Path, len(data), c.config.MaxFileBytes)
+ return types.MessageArtifact{}, false
+ }
+
+ // Give each blob a UUID-namespaced storage name so concurrent turns
+ // cannot collide, and so the storage key itself is unguessable from
+ // the outside (defence-in-depth on top of the /artifacts/:index
+ // endpoint's ownership check).
+ storageName := "artifact_" + uuid.NewString() + "_" + safeFileName(entry.Name)
+ storagePath, err := c.fileService.SaveBytes(ctx, data, tenantID, storageName, false)
+ if err != nil {
+ logger.Warnf(ctx, "[ArtifactCollector] upload artifact failed: session=%s path=%s err=%v",
+ sessionID, entry.Path, err)
+ return types.MessageArtifact{}, false
+ }
+
+ c.bindArtifactResource(ctx, storagePath, messageID)
+
+ return types.MessageArtifact{
+ URL: storagePath,
+ FileName: entry.Name,
+ FileType: strings.ToLower(filepath.Ext(entry.Name)),
+ FileSize: int64(len(data)),
+ SourcePath: entry.Path,
+ ModTime: modTime,
+ CreatedAt: time.Now().UTC(),
+ }, true
+}
+
+// bindArtifactResource records that the freshly-persisted artifact resource
+// is owned by its assistant message. Best-effort: a binding failure never
+// discards the artifact, because the file is already stored and remains
+// downloadable through the /artifacts endpoint regardless of the binding.
+//
+// The binding is only attempted when (a) the catalog is wired in, (b) we have
+// a message ID to own the resource, and (c) SaveBytes actually returned a
+// resource:// reference — i.e. the file service is resource-catalog-backed.
+// Raw provider paths (no catalog decorator) are left unbound rather than
+// generating spurious "invalid resource reference" errors.
+func (c *ArtifactCollector) bindArtifactResource(ctx context.Context, ref, messageID string) {
+ if c.catalog == nil || messageID == "" {
+ return
+ }
+ if _, ok := types.ParseResourcePath(ref); !ok {
+ return
+ }
+ if err := c.catalog.Bind(ctx, ref, artifactBindingOwnerType, messageID, artifactBindingRelation); err != nil {
+ logger.Warnf(ctx, "[ArtifactCollector] bind artifact resource failed: message=%s ref=%s err=%v",
+ messageID, ref, err)
+ }
+}
+
+// artifactKey is the string form of the (source_path, mtime) tuple used to
+// de-duplicate artifacts across messages. mtime is normalised to UTC + RFC3339
+// nano so equality is stable across time-zone or precision differences
+// between sandbox envd builds.
+func artifactKey(path string, mod time.Time) string {
+ if mod.IsZero() {
+ return path + "\x00"
+ }
+ return path + "\x00" + mod.UTC().Format(time.RFC3339Nano)
+}
+
+// safeFileName strips slashes and backslashes from the original name before
+// concatenating it into the storage key. The FileService may or may not
+// sanitise on its own; belt-and-suspenders here avoids provider-specific
+// surprises (e.g. object stores that treat "/" as delimiter).
+func safeFileName(name string) string {
+ name = strings.ReplaceAll(name, "/", "_")
+ name = strings.ReplaceAll(name, "\\", "_")
+ if name == "" {
+ return "unnamed"
+ }
+ return name
+}
diff --git a/internal/application/service/artifact_collector_store.go b/internal/application/service/artifact_collector_store.go
new file mode 100644
index 000000000..6617c0508
--- /dev/null
+++ b/internal/application/service/artifact_collector_store.go
@@ -0,0 +1,36 @@
+package service
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// messageRepoArtifactStore adapts interfaces.MessageRepository to the
+// SessionArtifactStore contract expected by ArtifactCollector. It is a thin
+// projection: KnownArtifacts is documented as best-effort, so we forward
+// repo errors verbatim and let the collector decide how to degrade.
+type messageRepoArtifactStore struct {
+ repo interfaces.MessageRepository
+}
+
+// NewMessageRepoArtifactStore wraps a MessageRepository so ArtifactCollector
+// can build its de-duplication set from every prior message of the session.
+func NewMessageRepoArtifactStore(repo interfaces.MessageRepository) SessionArtifactStore {
+ return &messageRepoArtifactStore{repo: repo}
+}
+
+// KnownArtifacts satisfies SessionArtifactStore.
+func (s *messageRepoArtifactStore) KnownArtifacts(
+ ctx context.Context, sessionID string,
+) ([]types.MessageArtifact, error) {
+ if s == nil || s.repo == nil || sessionID == "" {
+ return nil, nil
+ }
+ arts, err := s.repo.GetSessionArtifacts(ctx, sessionID)
+ if err != nil {
+ return nil, err
+ }
+ return arts, nil
+}
diff --git a/internal/application/service/artifact_collector_test.go b/internal/application/service/artifact_collector_test.go
new file mode 100644
index 000000000..c594b0911
--- /dev/null
+++ b/internal/application/service/artifact_collector_test.go
@@ -0,0 +1,527 @@
+package service
+
+import (
+ "context"
+ stderrors "errors"
+ "io"
+ "mime/multipart"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// -----------------------------------------------------------------------------
+// Test doubles
+// -----------------------------------------------------------------------------
+
+// fakeSandboxSource is an in-memory stand-in for SessionBoundManager that
+// records the calls the collector makes and returns pre-programmed
+// responses. Concrete tests populate `entries` (one map per session) and
+// `contents` (one map per absolute path).
+type fakeSandboxSource struct {
+ entries map[string][]sandbox.RemoteDirEntry
+ contents map[string][]byte
+
+ listErr error
+ readErr error
+
+ listCalls int
+ readCalls []string
+}
+
+func (f *fakeSandboxSource) ListSessionFiles(_ context.Context, sessionID, _ string) ([]sandbox.RemoteDirEntry, error) {
+ f.listCalls++
+ if f.listErr != nil {
+ return nil, f.listErr
+ }
+ return f.entries[sessionID], nil
+}
+
+func (f *fakeSandboxSource) ReadSessionFile(_ context.Context, _ string, path string) ([]byte, error) {
+ f.readCalls = append(f.readCalls, path)
+ if f.readErr != nil {
+ return nil, f.readErr
+ }
+ if data, ok := f.contents[path]; ok {
+ return data, nil
+ }
+ return nil, stderrors.New("fake source: not found: " + path)
+}
+
+// fakeStore lets a test declare which (path, mtime) tuples the collector
+// should treat as already recorded.
+type fakeStore struct {
+ prev []types.MessageArtifact
+ err error
+}
+
+func (s *fakeStore) KnownArtifacts(_ context.Context, _ string) ([]types.MessageArtifact, error) {
+ return s.prev, s.err
+}
+
+// fakeFileService captures uploads and returns a deterministic provider URL.
+// Only SaveBytes is exercised by the collector; the other methods are
+// implemented to satisfy interfaces.FileService but panic on use so a
+// regression that starts calling them doesn't fail silently.
+type fakeFileService struct {
+ saved map[string][]byte
+ saveErr error
+ seq int
+ tenantIDs []uint64
+}
+
+func (f *fakeFileService) CheckConnectivity(_ context.Context) error { return nil }
+
+func (f *fakeFileService) SaveFile(_ context.Context, _ *multipart.FileHeader, _ uint64, _ string) (string, error) {
+ panic("SaveFile should not be called by ArtifactCollector")
+}
+
+func (f *fakeFileService) SaveBytes(_ context.Context, data []byte, tenantID uint64, fileName string, _ bool) (string, error) {
+ if f.saveErr != nil {
+ return "", f.saveErr
+ }
+ if f.saved == nil {
+ f.saved = map[string][]byte{}
+ }
+ f.seq++
+ key := "fake://tenant-" + fileName
+ f.saved[key] = append([]byte(nil), data...)
+ f.tenantIDs = append(f.tenantIDs, tenantID)
+ return key, nil
+}
+
+func (f *fakeFileService) GetFile(_ context.Context, _ string) (io.ReadCloser, error) {
+ panic("GetFile should not be called by ArtifactCollector")
+}
+
+func (f *fakeFileService) GetFileURL(_ context.Context, _ string) (string, error) {
+ panic("GetFileURL should not be called by ArtifactCollector")
+}
+
+func (f *fakeFileService) DeleteFile(_ context.Context, _ string) error { return nil }
+
+func (f *fakeFileService) CopyFile(_ context.Context, _ string, _ uint64, _ string) (string, error) {
+ panic("CopyFile should not be called by ArtifactCollector")
+}
+
+// resourceRefFileService is a fileService whose SaveBytes returns a valid
+// resource:// reference, so the collector's binding path is exercised.
+type resourceRefFileService struct {
+ fakeFileService
+ handle string
+}
+
+func (f *resourceRefFileService) SaveBytes(_ context.Context, data []byte, tenantID uint64, fileName string, _ bool) (string, error) {
+ if f.saved == nil {
+ f.saved = map[string][]byte{}
+ }
+ f.seq++
+ ref := types.BuildResourcePath(f.handle)
+ f.saved[ref] = append([]byte(nil), data...)
+ f.tenantIDs = append(f.tenantIDs, tenantID)
+ return ref, nil
+}
+
+// bindCall records one Bind invocation for assertions.
+type bindCall struct {
+ ref string
+ ownerType string
+ ownerID string
+ relation string
+}
+
+// fakeCatalog captures Bind calls; every other ResourceCatalog method is a
+// no-op stub because the collector only ever calls Bind.
+type fakeCatalog struct {
+ binds []bindCall
+ bindErr error
+}
+
+func (c *fakeCatalog) Register(context.Context, uint64, string, interfaces.ResourceRegistration) (string, error) {
+ return "", nil
+}
+func (c *fakeCatalog) Resolve(context.Context, string) (*types.StoredResource, error) {
+ return nil, nil
+}
+func (c *fakeCatalog) ResolvePath(_ context.Context, v string) (string, *types.StoredResource, error) {
+ return v, nil, nil
+}
+func (c *fakeCatalog) Bind(_ context.Context, ref, ownerType, ownerID, relation string) error {
+ c.binds = append(c.binds, bindCall{ref, ownerType, ownerID, relation})
+ return c.bindErr
+}
+func (c *fakeCatalog) MarkDeleted(context.Context, string) error { return nil }
+func (c *fakeCatalog) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
+ return "", nil
+}
+func (c *fakeCatalog) ResolveAccessGrant(context.Context, string) (*types.StoredResource, error) {
+ return nil, nil
+}
+
+// -----------------------------------------------------------------------------
+// Tests
+// -----------------------------------------------------------------------------
+
+func newTestCollector(src *fakeSandboxSource, store *fakeStore, fs *fakeFileService, max int64) *ArtifactCollector {
+ // catalog is nil here: these tests use a fakeFileService that returns raw
+ // "fake://" paths, so no resource binding is attempted. Binding behaviour
+ // is covered separately in TestArtifactCollector_BindsResourceToMessage.
+ return NewArtifactCollector(src, fs, store, nil, ArtifactCollectorConfig{MaxFileBytes: max})
+}
+
+func TestArtifactCollector_CollectsNewFiles(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ {Name: "summary.txt", Path: "/workspace/output/summary.txt", Type: sandbox.RemoteEntryFile, Size: 3, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/report.pptx": []byte("PPTX"),
+ "/workspace/output/summary.txt": []byte("hey"),
+ },
+ }
+ store := &fakeStore{}
+ fs := &fakeFileService{}
+ c := newTestCollector(src, store, fs, 1<<20)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 2 {
+ t.Fatalf("Collect() len = %d, want 2 (%+v)", len(got), got)
+ }
+ // Files must be uploaded with the tenant ID passed by the caller.
+ for _, tID := range fs.tenantIDs {
+ if tID != 42 {
+ t.Fatalf("SaveBytes tenant = %d, want 42", tID)
+ }
+ }
+ // Both files must have populated URL + FileType + FileSize.
+ for _, art := range got {
+ if art.URL == "" {
+ t.Fatalf("artifact URL empty: %+v", art)
+ }
+ if art.FileType == "" {
+ t.Fatalf("artifact FileType empty: %+v", art)
+ }
+ if art.FileSize == 0 {
+ t.Fatalf("artifact FileSize zero: %+v", art)
+ }
+ }
+}
+
+func TestArtifactCollector_SkipsAlreadyKnown(t *testing.T) {
+ ctx := context.Background()
+ mod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/report.pptx": []byte("PPTX"),
+ },
+ }
+ store := &fakeStore{prev: []types.MessageArtifact{
+ {SourcePath: "/workspace/output/report.pptx", ModTime: mod},
+ }}
+ fs := &fakeFileService{}
+ c := newTestCollector(src, store, fs, 1<<20)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0 (dedupe should have kicked in)", len(got))
+ }
+ if len(fs.saved) != 0 {
+ t.Fatalf("SaveBytes should not have been called; saved=%v", fs.saved)
+ }
+ if len(src.readCalls) != 0 {
+ t.Fatalf("ReadSessionFile should not have been called; readCalls=%v", src.readCalls)
+ }
+}
+
+func TestArtifactCollector_ReattachesOnMtimeChange(t *testing.T) {
+ ctx := context.Background()
+ oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ // Same path as the known set, but a *newer* mtime — must be re-attached.
+ {Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:21:00Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/report.pptx": []byte("PPTX"),
+ },
+ }
+ store := &fakeStore{prev: []types.MessageArtifact{
+ {SourcePath: "/workspace/output/report.pptx", ModTime: oldMod},
+ }}
+ fs := &fakeFileService{}
+ c := newTestCollector(src, store, fs, 1<<20)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("Collect() len = %d, want 1 (mtime-change should re-attach)", len(got))
+ }
+ if len(fs.saved) != 1 {
+ t.Fatalf("SaveBytes calls = %d, want 1", len(fs.saved))
+ }
+}
+
+func TestArtifactCollector_SkipsOversize(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {Name: "huge.bin", Path: "/workspace/output/huge.bin", Type: sandbox.RemoteEntryFile, Size: 1024, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ {Name: "ok.txt", Path: "/workspace/output/ok.txt", Type: sandbox.RemoteEntryFile, Size: 3, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/huge.bin": bytesN(2048),
+ "/workspace/output/ok.txt": []byte("hey"),
+ },
+ }
+ fs := &fakeFileService{}
+ c := newTestCollector(src, &fakeStore{}, fs, 100)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("Collect() len = %d, want 1 (oversize file must be skipped)", len(got))
+ }
+ if got[0].FileName != "ok.txt" {
+ t.Fatalf("Collect() kept the wrong file: %+v", got[0])
+ }
+}
+
+func TestArtifactCollector_SkipsOversizeAfterRead(t *testing.T) {
+ // Envd can report a stale size while the file grows; the collector must
+ // enforce the cap against the actual bytes too.
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {Name: "lying.bin", Path: "/workspace/output/lying.bin", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/lying.bin": bytesN(2048),
+ },
+ }
+ fs := &fakeFileService{}
+ c := newTestCollector(src, &fakeStore{}, fs, 100)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0", len(got))
+ }
+}
+
+func TestArtifactCollector_EmptyWhenNoEntries(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{}
+ c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0", len(got))
+ }
+}
+
+func TestArtifactCollector_EmptyWhenNoSessionID(t *testing.T) {
+ // The collector treats empty session ID as "nothing to do" — the design
+ // spec forbids sandbox lookups for chat-only sessions.
+ ctx := context.Background()
+ src := &fakeSandboxSource{}
+ c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
+ got, err := c.Collect(ctx, "", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0", len(got))
+ }
+ if src.listCalls != 0 {
+ t.Fatalf("expected 0 list calls for empty session id, got %d", src.listCalls)
+ }
+}
+
+func TestArtifactCollector_ListErrorDegrades(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{listErr: stderrors.New("envd timeout")}
+ c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v (should degrade gracefully)", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0", len(got))
+ }
+}
+
+func TestArtifactCollector_UploadFailureIsPerFile(t *testing.T) {
+ // A single failed upload must NOT abort the whole batch — the other
+ // files should still be persisted, matching the best-effort contract.
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {Name: "a.txt", Path: "/workspace/output/a.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ {Name: "b.txt", Path: "/workspace/output/b.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/a.txt": []byte("a"),
+ "/workspace/output/b.txt": []byte("b"),
+ },
+ }
+ // FileService fails on every call — both files should be skipped without
+ // propagating an error.
+ fs := &fakeFileService{saveErr: stderrors.New("s3 dead")}
+ c := newTestCollector(src, &fakeStore{}, fs, 1<<20)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v (want best-effort)", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0 (all uploads failed)", len(got))
+ }
+}
+
+func TestArtifactCollector_FiltersDirectories(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ // The production ListSessionFiles never yields dirs, but the
+ // collector must defensively skip anything with Type=="dir"
+ // so alternate SandboxArtifactSource impls stay safe.
+ {Name: "sub", Path: "/workspace/output/sub", Type: sandbox.RemoteEntryDir, Size: 0, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ {Name: "a.txt", Path: "/workspace/output/a.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/a.txt": []byte("a"),
+ },
+ }
+ c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("Collect() len = %d, want 1 (dir must be skipped)", len(got))
+ }
+ if !strings.HasSuffix(got[0].SourcePath, "a.txt") {
+ t.Fatalf("wrong file kept: %+v", got[0])
+ }
+}
+
+func TestArtifactCollector_BindsResourceToMessage(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ },
+ },
+ contents: map[string][]byte{
+ "/workspace/output/report.pptx": []byte("PPTX"),
+ },
+ }
+ // 22-char handle so BuildResourcePath yields a valid resource:// ref.
+ fs := &resourceRefFileService{handle: "abcdefghijklmnopqrstuv"}
+ cat := &fakeCatalog{}
+ c := NewArtifactCollector(src, fs, &fakeStore{}, cat, ArtifactCollectorConfig{MaxFileBytes: 1 << 20})
+
+ got, err := c.Collect(ctx, "sess-1", "msg-42", 7, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("Collect() len = %d, want 1", len(got))
+ }
+ if len(cat.binds) != 1 {
+ t.Fatalf("Bind calls = %d, want 1 (%+v)", len(cat.binds), cat.binds)
+ }
+ b := cat.binds[0]
+ if b.ownerType != "message" || b.ownerID != "msg-42" || b.relation != "artifact" {
+ t.Fatalf("unexpected binding: %+v", b)
+ }
+ if _, ok := types.ParseResourcePath(b.ref); !ok {
+ t.Fatalf("binding ref is not a resource reference: %q", b.ref)
+ }
+}
+
+func TestArtifactCollector_BindFailureDoesNotDropArtifact(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {Name: "a.txt", Path: "/workspace/output/a.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
+ },
+ },
+ contents: map[string][]byte{"/workspace/output/a.txt": []byte("a")},
+ }
+ fs := &resourceRefFileService{handle: "abcdefghijklmnopqrstuv"}
+ cat := &fakeCatalog{bindErr: stderrors.New("db down")}
+ c := NewArtifactCollector(src, fs, &fakeStore{}, cat, ArtifactCollectorConfig{MaxFileBytes: 1 << 20})
+
+ got, err := c.Collect(ctx, "sess-1", "msg-1", 7, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("Collect() len = %d, want 1 (bind failure must not drop the artifact)", len(got))
+ }
+}
+
+// mustParseTime parses an RFC3339 timestamp for test data. It fails the
+// program on error because test fixtures should never contain malformed
+// timestamps.
+func mustParseTime(raw string) time.Time {
+ t, err := time.Parse(time.RFC3339Nano, raw)
+ if err != nil {
+ t, err = time.Parse(time.RFC3339, raw)
+ }
+ if err != nil {
+ panic("mustParseTime: " + err.Error())
+ }
+ return t
+}
+
+// bytesN returns a byte slice of length n filled with 'x'. Kept local to
+// avoid pulling in a dependency; matches "generate N bytes" test helpers
+// elsewhere in the codebase.
+func bytesN(n int) []byte {
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = 'x'
+ }
+ return b
+}
diff --git a/internal/application/service/message.go b/internal/application/service/message.go
index bc6adfad4..367ee36c3 100644
--- a/internal/application/service/message.go
+++ b/internal/application/service/message.go
@@ -479,6 +479,19 @@ func (s *messageService) GetChatHistoryKBStats(ctx context.Context) (*types.Chat
return stats, nil
}
+// GetSessionArtifacts returns every skill-produced artifact recorded against
+// any assistant message of the session. Thin pass-through to the repository:
+// the collector and session cleanup both need it, and centralising it here
+// keeps tests able to inject a stub MessageService.
+func (s *messageService) GetSessionArtifacts(
+ ctx context.Context, sessionID string,
+) (types.MessageArtifacts, error) {
+ if sessionID == "" {
+ return types.MessageArtifacts{}, nil
+ }
+ return s.messageRepo.GetSessionArtifacts(ctx, sessionID)
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// Message Search (Hybrid: Keyword + KB Vector Search)
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/internal/application/service/model_delete_test.go b/internal/application/service/model_delete_test.go
index ad66d4f93..ea726c3f0 100644
--- a/internal/application/service/model_delete_test.go
+++ b/internal/application/service/model_delete_test.go
@@ -71,6 +71,12 @@ func (s *stubAgentRepoForModelDelete) DeleteAgent(context.Context, string, uint6
func (s *stubAgentRepoForModelDelete) CountByModelID(context.Context, uint64, string) (int64, error) {
return s.count, nil
}
+func (s *stubAgentRepoForModelDelete) CountBySandboxConfigID(context.Context, uint64, string) (int64, error) {
+ return 0, nil
+}
+func (s *stubAgentRepoForModelDelete) ListNamesBySandboxConfigID(context.Context, uint64, string) ([]string, error) {
+ return nil, nil
+}
type stubModelRepoForDelete struct {
model *types.Model
diff --git a/internal/application/service/session.go b/internal/application/service/session.go
index 801bb5bba..07b12917e 100644
--- a/internal/application/service/session.go
+++ b/internal/application/service/session.go
@@ -16,6 +16,7 @@ import (
"github.com/google/uuid"
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
+ "github.com/Tencent/WeKnora/internal/sandbox"
)
func sessionUserIDFromContext(ctx context.Context) string {
@@ -123,6 +124,10 @@ type sessionService struct {
webSearchProviderRepo interfaces.WebSearchProviderRepository // Repository for web search provider entities
kbShareService interfaces.KBShareService // Service for KB sharing operations
suggestionRepo interfaces.MessageSuggestionRepository
+ sandboxMgr sandbox.Manager // Default sandbox backend; used to reclaim per-session MicroVMs on delete
+ sandboxResolver sandbox.TenantSandboxResolver
+ sandboxPinner *SessionSandboxPinner
+ sandboxPolicy WorkspaceSandboxPolicy
}
// NewSessionService creates a new session service instance with all required dependencies
@@ -140,6 +145,10 @@ func NewSessionService(cfg *config.Config,
webSearchProviderRepo interfaces.WebSearchProviderRepository,
kbShareService interfaces.KBShareService,
suggestionRepo interfaces.MessageSuggestionRepository,
+ sandboxMgr sandbox.Manager,
+ sandboxResolver sandbox.TenantSandboxResolver,
+ sandboxPinner *SessionSandboxPinner,
+ sandboxPolicy WorkspaceSandboxPolicy,
) interfaces.SessionService {
return &sessionService{
cfg: cfg,
@@ -156,6 +165,10 @@ func NewSessionService(cfg *config.Config,
webSearchProviderRepo: webSearchProviderRepo,
kbShareService: kbShareService,
suggestionRepo: suggestionRepo,
+ sandboxMgr: sandboxMgr,
+ sandboxResolver: sandboxResolver,
+ sandboxPinner: sandboxPinner,
+ sandboxPolicy: sandboxPolicy,
}
}
@@ -470,11 +483,27 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
}
}()
+ // NOTE: Skill-generated artifact blobs are intentionally NOT purged here.
+ // Their lifecycle mirrors messages, which are soft-deleted (deleted_at
+ // timestamp) rather than physically removed. Hard-deleting the blobs on a
+ // soft session delete would (a) diverge from message semantics, (b) make
+ // any future "restore soft-deleted session" flow silently broken, and (c)
+ // leave 404s in the download endpoint if the message row is ever surfaced
+ // again. A dedicated GC job or explicit hard-delete API is the right
+ // place to reclaim storage — not this soft-delete path.
+
// Cleanup temporary KB stored in Redis for this session
if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", id, err)
}
+ if s.suggestionRepo != nil {
+ if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, id); err != nil {
+ logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", id, err)
+ }
+ }
+
+ s.destroyBoundSandbox(ctx, id)
// Delete session from repository
rows, err := s.sessionRepo.Delete(ctx, tenantID, userID, id)
if err != nil {
@@ -487,11 +516,6 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
if rows == 0 {
return apperrors.ErrSessionNotFound
}
- if s.suggestionRepo != nil {
- if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, id); err != nil {
- logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", id, err)
- }
- }
return nil
}
@@ -539,6 +563,13 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", id, err)
}
+ // Artifact blobs are kept alongside soft-deleted messages — see
+ // DeleteSession for the rationale.
+ }
+
+ // Tear down sandboxes while session rows (and pins) are still readable.
+ for _, id := range visibleIDs {
+ s.destroyBoundSandbox(ctx, id)
}
// Batch delete sessions from repository
@@ -589,6 +620,15 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, session.ID); err != nil {
logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", session.ID, err)
}
+ // Artifact blobs are kept alongside soft-deleted messages — see
+ // DeleteSession for the rationale.
+ }
+ }
+
+ // Tear down sandboxes while session rows (and pins) are still readable.
+ if sessions != nil {
+ for _, session := range sessions {
+ s.destroyBoundSandbox(ctx, session.ID)
}
}
@@ -610,6 +650,60 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
return nil
}
+// 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.
+//
+// Errors are logged but never propagated: sandbox teardown must not block
+// session deletion. Call this while the session row is still live so the
+// sandbox_config_id pin resolves to the correct named backend.
+func (s *sessionService) destroyBoundSandbox(ctx context.Context, sessionID string) {
+ if sessionID == "" {
+ return
+ }
+ // Resolve the workspace's own manager: the sandbox to release lives on
+ // whichever backend that workspace is configured for, not necessarily the
+ // process-wide default.
+ tenantID, _ := types.TenantIDFromContext(ctx)
+ configID, err := sandboxConfigForExistingSandbox(ctx, s.sandboxPinner, sessionID)
+ if err != nil {
+ logger.Warnf(ctx, "Failed to read sandbox pin for session %s cleanup: %v", sessionID, err)
+ return
+ }
+ // An empty pin normally means there is nothing to destroy, but sessions
+ // whose sandbox predates the pin column also read as empty. Falling through
+ // to the default manager keeps those reachable: DestroySession is a cheap
+ // binding lookup that no-ops when the session truly has no sandbox, whereas
+ // skipping would abandon a paused instance that keeps billing.
+ mgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy)
+ if err != nil {
+ logger.Warnf(ctx, "Failed to resolve sandbox for session %s cleanup: %v", sessionID, err)
+ return
+ }
+ if mgr == nil {
+ return
+ }
+ destroyer, ok := mgr.(interface {
+ DestroySession(context.Context, string) error
+ })
+ if !ok {
+ return
+ }
+ if err := destroyer.DestroySession(ctx, sessionID); err != nil {
+ logger.Warnf(ctx, "Failed to destroy sandbox for session %s: %v", sessionID, err)
+ return
+ }
+ if s.sandboxPinner != nil {
+ if err := s.sandboxPinner.Clear(ctx, sessionID); err != nil {
+ logger.Warnf(ctx, "Failed to clear sandbox pin for session %s: %v", sessionID, err)
+ }
+ }
+}
+
// GenerateTitle generates a title for the current conversation content
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
func (s *sessionService) GenerateTitle(ctx context.Context,
diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go
index aed7b305d..c194cd26d 100644
--- a/internal/application/service/session_agent_qa.go
+++ b/internal/application/service/session_agent_qa.go
@@ -24,6 +24,9 @@ func (s *sessionService) AgentQA(
eventBus *event.EventBus,
) error {
sessionID := req.Session.ID
+ // Propagate the session ID so stateful sandbox backends (CubeSandbox) can
+ // bind script execution to a per-session MicroVM instance.
+ ctx = types.WithSessionID(ctx, sessionID)
sessionJSON, err := json.Marshal(req.Session)
if err != nil {
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
@@ -140,6 +143,36 @@ func (s *sessionService) AgentQA(
llmContext = []chat.Message{}
}
+ // Reconcile all durable session attachments into the session's remote
+ // sandbox before the model can request shell or skill execution. The
+ // durable storage URL — not the ephemeral sandbox path — remains the
+ // source of truth. Gated on the sandbox manager advertising a session
+ // filesystem capability so provider-neutral wiring (Cube today, E2B
+ // tomorrow) drops in without touching this call site.
+ var stagedAttachments []stagedSessionAttachment
+ stager, ok := s.agentService.(sessionAttachmentStager)
+ if !ok {
+ return errors.New("agent service does not support session attachment staging")
+ }
+ // Probe the backend this session's sandbox actually runs on. Gating on the
+ // process-wide manager instead would skip staging whenever the deployment
+ // default is docker/local but the agent selected a named Cube/E2B config —
+ // the tools would still run remotely, against an empty /workspace/input.
+ inputStore, storeErr := stager.sessionSandboxInputStore(ctx, sessionID, agentConfig.SandboxConfigID)
+ if storeErr != nil {
+ return fmt.Errorf("resolve sandbox file store for session %s: %w", sessionID, storeErr)
+ }
+ if inputStore != nil {
+ sessionAttachments, loadErr := s.messageRepo.GetSessionAttachments(ctx, sessionID)
+ if loadErr != nil {
+ return fmt.Errorf("load session attachments for sandbox staging: %w", loadErr)
+ }
+ stagedAttachments, err = stager.stageSessionAttachments(ctx, sessionID, agentConfig.SandboxConfigID, sessionAttachments)
+ if err != nil {
+ return fmt.Errorf("restore session attachments into sandbox: %w", err)
+ }
+ }
+
// Create agent engine with EventBus
logger.Info(ctx, "Creating agent engine")
engine, err := s.agentService.CreateAgentEngine(
@@ -183,6 +216,10 @@ func (s *sessionService) AgentQA(
agentQuery += req.Attachments.BuildPrompt()
logger.Infof(ctx, "Appended %d attachment(s) to agent query", len(req.Attachments))
}
+ if manifest := buildSandboxAttachmentsPrompt(stagedAttachments); manifest != "" {
+ agentQuery += manifest
+ logger.Infof(ctx, "Appended %d staged sandbox attachment path(s) to agent query", len(stagedAttachments))
+ }
// Scope envelopes (runtime_context / must_use) are injected per LLM call inside
// the agent engine only; we intentionally do not persist them on user messages
@@ -499,6 +536,7 @@ func (s *sessionService) configureSkillsFromAgent(
if customAgent == nil {
return
}
+ agentConfig.SandboxConfigID = customAgent.Config.SandboxConfigID
// When sandbox is disabled, skills cannot be enabled (no script execution environment)
sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")
if sandboxMode == "" || sandboxMode == "disabled" {
diff --git a/internal/application/service/session_attachment_staging.go b/internal/application/service/session_attachment_staging.go
new file mode 100644
index 000000000..c4287773d
--- /dev/null
+++ b/internal/application/service/session_attachment_staging.go
@@ -0,0 +1,235 @@
+package service
+
+import (
+ "context"
+ "crypto/sha256"
+ "fmt"
+ "io"
+ "path"
+ "sort"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
+)
+
+type stagedSessionAttachment struct {
+ Name string
+ FileType string
+ Size int64
+ Path string
+}
+
+// sessionSandboxFileStore returns the manager's effective session filesystem
+// capability, or nil when the backend cannot support it. Centralised so
+// callers never resurrect a Cube-specific type check.
+func sessionSandboxFileStore(mgr sandbox.Manager) sandbox.SessionFileStore {
+ provider, ok := mgr.(sandbox.SessionCapabilityProvider)
+ if !ok || provider == nil {
+ return nil
+ }
+ return provider.SessionFileStore()
+}
+
+// sessionSandboxShellExecutor is the shell-execution counterpart of
+// sessionSandboxFileStore.
+func sessionSandboxShellExecutor(mgr sandbox.Manager) sandbox.SessionShellExecutor {
+ provider, ok := mgr.(sandbox.SessionCapabilityProvider)
+ if !ok || provider == nil {
+ return nil
+ }
+ return provider.SessionShellExecutor()
+}
+
+// sessionAttachmentStager is the agentService surface the QA pipeline needs to
+// stage attachments. Declared as a named interface so the runtime type
+// assertion in session_agent_qa.go has one definition to drift against.
+type sessionAttachmentStager interface {
+ sessionSandboxInputStore(
+ ctx context.Context, sessionID, agentSandboxConfigID string,
+ ) (sandbox.SessionFileStore, error)
+ stageSessionAttachments(
+ ctx context.Context, sessionID, agentSandboxConfigID string,
+ attachments types.MessageAttachments,
+ ) ([]stagedSessionAttachment, error)
+}
+
+// sessionSandboxInputStore resolves the session filesystem capability of the
+// backend this session's sandbox actually runs on.
+//
+// Callers must gate staging on this rather than on the process-wide manager: a
+// workspace can select a named Cube/E2B config while the deployment default is
+// docker/local, and in that combination the agent still registers shell/skill
+// tools against the remote sandbox, so its attachments have to be staged too.
+func (s *agentService) sessionSandboxInputStore(
+ ctx context.Context,
+ sessionID string,
+ agentSandboxConfigID string,
+) (sandbox.SessionFileStore, error) {
+ if s == nil {
+ return nil, nil
+ }
+ tenantID, _ := types.TenantIDFromContext(ctx)
+ configID, err := sandboxConfigForExecution(ctx, s.sandboxPinner, sessionID, agentSandboxConfigID)
+ if err != nil {
+ return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)
+ }
+ mgr, err := resolveTenantSandboxForConfig(
+ ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy,
+ )
+ if err != nil {
+ return nil, err
+ }
+ return sessionSandboxFileStore(mgr), nil
+}
+
+// stageSessionAttachments reconciles /workspace/input with the durable
+// attachment inventory. It is gated on the sandbox manager advertising a
+// session filesystem capability; other backends retain prompt-extracted
+// attachment content and never receive host file paths.
+func (s *agentService) stageSessionAttachments(
+ ctx context.Context,
+ sessionID string,
+ agentSandboxConfigID string,
+ attachments types.MessageAttachments,
+) ([]stagedSessionAttachment, error) {
+ if s == nil {
+ return nil, nil
+ }
+ store, err := s.sessionSandboxInputStore(ctx, sessionID, agentSandboxConfigID)
+ if err != nil {
+ return nil, err
+ }
+ if store == nil {
+ return nil, nil
+ }
+ if s.fileService == nil && len(attachments) > 0 {
+ return nil, fmt.Errorf("file service is unavailable for session input staging")
+ }
+
+ attachments = deduplicateSessionAttachments(attachments)
+ existingEntries, err := store.ListSessionFiles(ctx, sessionID, sandbox.SessionInputRoot)
+ if err != nil {
+ return nil, fmt.Errorf("list staged session inputs: %w", err)
+ }
+ existing := make(map[string]sandbox.RemoteDirEntry, len(existingEntries))
+ for _, entry := range existingEntries {
+ existing[path.Clean(entry.Path)] = entry
+ }
+
+ desired := make(map[string]struct{}, len(attachments))
+ staged := make([]stagedSessionAttachment, 0, len(attachments))
+ maxBytes := int64(secutils.GetMaxFileSizeMB()) * 1024 * 1024
+ for _, attachment := range attachments {
+ remotePath, pathErr := sandboxAttachmentPath(attachment)
+ if pathErr != nil {
+ return nil, pathErr
+ }
+ desired[remotePath] = struct{}{}
+
+ entry, present := existing[remotePath]
+ if !present || attachment.FileSize <= 0 || entry.Size != attachment.FileSize {
+ reader, getErr := s.fileService.GetFile(ctx, attachment.URL)
+ if getErr != nil {
+ return nil, fmt.Errorf("open attachment %q: %w", attachment.FileName, getErr)
+ }
+ content, readErr := io.ReadAll(io.LimitReader(reader, maxBytes+1))
+ closeErr := reader.Close()
+ if readErr != nil {
+ return nil, fmt.Errorf("read attachment %q: %w", attachment.FileName, readErr)
+ }
+ if closeErr != nil {
+ return nil, fmt.Errorf("close attachment %q: %w", attachment.FileName, closeErr)
+ }
+ if int64(len(content)) > maxBytes {
+ return nil, fmt.Errorf("attachment %q exceeds sandbox staging limit of %d bytes", attachment.FileName, maxBytes)
+ }
+ if writeErr := store.WriteSessionInputFile(ctx, sessionID, remotePath, content); writeErr != nil {
+ return nil, fmt.Errorf("stage attachment %q: %w", attachment.FileName, writeErr)
+ }
+ attachment.FileSize = int64(len(content))
+ }
+
+ staged = append(staged, stagedSessionAttachment{
+ Name: attachment.FileName,
+ FileType: attachment.FileType,
+ Size: attachment.FileSize,
+ Path: remotePath,
+ })
+ }
+
+ // Remove inputs whose durable message attachment no longer exists.
+ for filePath := range existing {
+ if _, keep := desired[filePath]; !keep {
+ if err := store.RemoveSessionInputPath(ctx, sessionID, filePath); err != nil {
+ return nil, fmt.Errorf("remove stale session input %s: %w", filePath, err)
+ }
+ }
+ }
+
+ sort.SliceStable(staged, func(i, j int) bool { return staged[i].Path < staged[j].Path })
+ return staged, nil
+}
+
+func deduplicateSessionAttachments(attachments types.MessageAttachments) types.MessageAttachments {
+ seen := make(map[string]struct{}, len(attachments))
+ out := make(types.MessageAttachments, 0, len(attachments))
+ for _, attachment := range attachments {
+ url := strings.TrimSpace(attachment.URL)
+ if url == "" {
+ continue
+ }
+ if _, exists := seen[url]; exists {
+ continue
+ }
+ seen[url] = struct{}{}
+ out = append(out, attachment)
+ }
+ return out
+}
+
+func sandboxAttachmentPath(attachment types.MessageAttachment) (string, error) {
+ url := strings.TrimSpace(attachment.URL)
+ if url == "" {
+ return "", fmt.Errorf("attachment %q has no durable storage URL", attachment.FileName)
+ }
+ fileName, err := secutils.SafeFileName(attachment.FileName)
+ if err != nil {
+ return "", fmt.Errorf("unsafe attachment filename %q: %w", attachment.FileName, err)
+ }
+ sum := sha256.Sum256([]byte(url))
+ return path.Join(sandbox.SessionInputRoot, fmt.Sprintf("%x", sum[:6]), fileName), nil
+}
+
+func buildSandboxAttachmentsPrompt(attachments []stagedSessionAttachment) string {
+ if len(attachments) == 0 {
+ return ""
+ }
+ var b strings.Builder
+ b.WriteString("\n\n<sandbox_attachments root=\"/workspace/input\">\n")
+ for _, attachment := range attachments {
+ fmt.Fprintf(
+ &b,
+ " <file name=\"%s\" type=\"%s\" size_bytes=\"%d\" path=\"%s\" />\n",
+ escapeAttachmentXML(attachment.Name),
+ escapeAttachmentXML(attachment.FileType),
+ attachment.Size,
+ escapeAttachmentXML(attachment.Path),
+ )
+ }
+ b.WriteString(" <instruction>Use these absolute paths as read-only inputs for shell commands or skill script arguments. Write generated files only under $WEKNORA_SKILL_OUTPUT_DIR.</instruction>\n")
+ b.WriteString("</sandbox_attachments>")
+ return b.String()
+}
+
+func escapeAttachmentXML(value string) string {
+ replacer := strings.NewReplacer(
+ "&", "&amp;",
+ "<", "&lt;",
+ ">", "&gt;",
+ "\"", "&quot;",
+ "'", "&apos;",
+ )
+ return replacer.Replace(value)
+}
diff --git a/internal/application/service/session_attachment_staging_test.go b/internal/application/service/session_attachment_staging_test.go
new file mode 100644
index 000000000..783be3ff3
--- /dev/null
+++ b/internal/application/service/session_attachment_staging_test.go
@@ -0,0 +1,179 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "mime/multipart"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stagingFileService struct {
+ files map[string][]byte
+ getCalls map[string]int
+}
+
+func (f *stagingFileService) CheckConnectivity(context.Context) error { return nil }
+func (f *stagingFileService) SaveFile(context.Context, *multipart.FileHeader, uint64, string) (string, error) {
+ panic("unexpected SaveFile")
+}
+func (f *stagingFileService) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) {
+ panic("unexpected SaveBytes")
+}
+func (f *stagingFileService) GetFile(_ context.Context, filePath string) (io.ReadCloser, error) {
+ if f.getCalls == nil {
+ f.getCalls = make(map[string]int)
+ }
+ f.getCalls[filePath]++
+ return io.NopCloser(bytes.NewReader(f.files[filePath])), nil
+}
+func (f *stagingFileService) GetFileURL(context.Context, string) (string, error) {
+ panic("unexpected GetFileURL")
+}
+func (f *stagingFileService) DeleteFile(context.Context, string) error { return nil }
+func (f *stagingFileService) CopyFile(context.Context, string, uint64, string) (string, error) {
+ panic("unexpected CopyFile")
+}
+
+// stagingSandboxManager is a test double that satisfies both the Manager
+// contract and the SessionCapabilityProvider capability accessor. It stores
+// in-memory files so a staging test can round-trip attachments without a
+// real sandbox.
+type stagingSandboxManager struct {
+ sandboxType sandbox.SandboxType
+ files map[string][]byte
+ writes []string
+ removes []string
+
+ // disableFiles lets a test simulate a manager that advertises no
+ // session filesystem capability (e.g. Local fallback engaged).
+ disableFiles bool
+}
+
+func (m *stagingSandboxManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
+ panic("unexpected Execute")
+}
+func (m *stagingSandboxManager) Cleanup(context.Context) error { return nil }
+func (m *stagingSandboxManager) GetSandbox() sandbox.Sandbox { return nil }
+func (m *stagingSandboxManager) GetType() sandbox.SandboxType { return m.sandboxType }
+
+func (m *stagingSandboxManager) SessionShellExecutor() sandbox.SessionShellExecutor { return nil }
+func (m *stagingSandboxManager) SessionFileStore() sandbox.SessionFileStore {
+ if m.disableFiles {
+ return nil
+ }
+ return m
+}
+
+func (m *stagingSandboxManager) EnsureSessionDir(context.Context, string, string) error {
+ return nil
+}
+func (m *stagingSandboxManager) StatSessionFile(context.Context, string, string) (*sandbox.RemoteStatEntry, error) {
+ panic("unexpected StatSessionFile")
+}
+func (m *stagingSandboxManager) ReadSessionFile(context.Context, string, string) ([]byte, error) {
+ panic("unexpected ReadSessionFile")
+}
+func (m *stagingSandboxManager) ListSessionFiles(context.Context, string, string) ([]sandbox.RemoteDirEntry, error) {
+ entries := make([]sandbox.RemoteDirEntry, 0, len(m.files))
+ for filePath, content := range m.files {
+ entries = append(entries, sandbox.RemoteDirEntry{Path: filePath, Size: int64(len(content)), Type: sandbox.RemoteEntryFile})
+ }
+ return entries, nil
+}
+func (m *stagingSandboxManager) WriteSessionInputFile(_ context.Context, _ string, filePath string, content []byte) error {
+ if m.files == nil {
+ m.files = make(map[string][]byte)
+ }
+ m.files[filePath] = append([]byte(nil), content...)
+ m.writes = append(m.writes, filePath)
+ return nil
+}
+func (m *stagingSandboxManager) RemoveSessionInputPath(_ context.Context, _ string, targetPath string) error {
+ for filePath := range m.files {
+ if filePath == targetPath || strings.HasPrefix(filePath, targetPath+"/") {
+ delete(m.files, filePath)
+ }
+ }
+ m.removes = append(m.removes, targetPath)
+ return nil
+}
+
+func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {
+ t.Setenv("WEKNORA_SANDBOX_MODE", "cube")
+
+ attachment := types.MessageAttachment{
+ URL: "local://tenant/attachment-1",
+ FileName: "report.pdf",
+ FileType: ".pdf",
+ FileSize: 7,
+ }
+ remotePath, err := sandboxAttachmentPath(attachment)
+ require.NoError(t, err)
+ stalePath := sandbox.SessionInputRoot + "/stale/old.txt"
+ manager := &stagingSandboxManager{
+ sandboxType: sandbox.SandboxTypeCube,
+ files: map[string][]byte{stalePath: []byte("old")},
+ }
+ fileService := &stagingFileService{
+ files: map[string][]byte{attachment.URL: []byte("content")},
+ }
+ service := &agentService{sandboxMgr: manager, fileService: fileService}
+
+ staged, err := service.stageSessionAttachments(
+ context.Background(),
+ "session-1",
+ "",
+ types.MessageAttachments{attachment, attachment},
+ )
+
+ require.NoError(t, err)
+ require.Len(t, staged, 1)
+ assert.Equal(t, remotePath, staged[0].Path)
+ assert.Equal(t, []string{remotePath}, manager.writes)
+ assert.Equal(t, 1, fileService.getCalls[attachment.URL])
+ assert.NotEmpty(t, manager.removes)
+ assert.NotContains(t, manager.files, stalePath)
+
+ // The second reconciliation sees the same path and size and avoids storage IO.
+ _, err = service.stageSessionAttachments(context.Background(), "session-1", "", types.MessageAttachments{attachment})
+ require.NoError(t, err)
+ assert.Equal(t, 1, fileService.getCalls[attachment.URL])
+}
+
+func TestStageSessionAttachmentsSkipsWhenNoFilesystemCapability(t *testing.T) {
+ t.Setenv("WEKNORA_SANDBOX_MODE", "local")
+
+ // disableFiles=true simulates any manager without a session filesystem
+ // capability (Local/Docker/Disabled DefaultManager, or a
+ // SessionBoundManager whose remote provider fell back to Local).
+ manager := &stagingSandboxManager{
+ sandboxType: sandbox.SandboxTypeLocal,
+ disableFiles: true,
+ }
+ service := &agentService{sandboxMgr: manager, fileService: &stagingFileService{}}
+
+ staged, err := service.stageSessionAttachments(context.Background(), "session-1", "", types.MessageAttachments{{
+ URL: "local://tenant/file", FileName: "file.txt",
+ }})
+
+ require.NoError(t, err)
+ assert.Empty(t, staged)
+ assert.Empty(t, manager.writes)
+}
+
+func TestBuildSandboxAttachmentsPromptEscapesMetadata(t *testing.T) {
+ prompt := buildSandboxAttachmentsPrompt([]stagedSessionAttachment{{
+ Name: "a<&>.txt", FileType: ".txt", Size: 3, Path: "/workspace/input/hash/a.txt",
+ }})
+
+ assert.Contains(t, prompt, `name="a&lt;&amp;&gt;.txt"`)
+ assert.Contains(t, prompt, `path="/workspace/input/hash/a.txt"`)
+ assert.Contains(t, prompt, "read-only inputs")
+}
diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go
index 938f1048f..f3139158a 100644
--- a/internal/application/service/session_knowledge_qa.go
+++ b/internal/application/service/session_knowledge_qa.go
@@ -202,6 +202,9 @@ func (s *sessionService) KnowledgeQA(
// Start knowledge QA event processing (set session tenant so pipeline session/message lookups use session owner)
ctx = context.WithValue(ctx, types.SessionTenantIDContextKey, req.Session.TenantID)
+ // Propagate the session ID so stateful sandbox backends (CubeSandbox) can
+ // bind script execution to a per-session MicroVM instance.
+ ctx = types.WithSessionID(ctx, req.Session.ID)
logger.Info(ctx, "Triggering question answering event")
setupSpan.Finish(map[string]interface{}{
"stages": len(pipeline),
diff --git a/internal/application/service/session_sandbox_entry_test.go b/internal/application/service/session_sandbox_entry_test.go
new file mode 100644
index 000000000..e6b8d7ebd
--- /dev/null
+++ b/internal/application/service/session_sandbox_entry_test.go
@@ -0,0 +1,144 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// stubSandboxResolver stands in for the per-config resolver. Its presence is
+// what makes the collector take the resolving branch at all.
+type stubSandboxResolver struct {
+ mgr sandbox.Manager
+ err error
+}
+
+func (s stubSandboxResolver) Resolve(context.Context, uint64, string) (sandbox.Manager, error) {
+ return s.mgr, s.err
+}
+
+// artifactFallbackManager is a minimal sandbox.Manager that delegates artifact
+// reads to a SandboxArtifactSource — used when tests exercise sentinel pins.
+type artifactFallbackManager struct {
+ source SandboxArtifactSource
+}
+
+func (m *artifactFallbackManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
+ panic("unexpected Execute")
+}
+func (m *artifactFallbackManager) Cleanup(context.Context) error { return nil }
+func (m *artifactFallbackManager) GetSandbox() sandbox.Sandbox { return nil }
+func (m *artifactFallbackManager) GetType() sandbox.SandboxType {
+ return sandbox.SandboxTypeCube
+}
+
+func (m *artifactFallbackManager) ListSessionFiles(ctx context.Context, sessionID, dir string) ([]sandbox.RemoteDirEntry, error) {
+ return m.source.ListSessionFiles(ctx, sessionID, dir)
+}
+func (m *artifactFallbackManager) ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error) {
+ return m.source.ReadSessionFile(ctx, sessionID, path)
+}
+
+// Execution decides the config; every later operation must follow the pin, so
+// that re-pointing the agent mid-conversation cannot split a session across
+// two backends.
+func TestSandboxConfigForExecutionPinsAgentChoice(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+
+ got, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", got)
+
+ // Admin re-points the agent at cfg-b: the live sandbox stays on cfg-a.
+ got, err = sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-b")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", got)
+}
+
+func TestSandboxConfigForExistingSandboxReturnsEmptyWhenUnpinned(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+
+ got, err := sandboxConfigForExistingSandbox(context.Background(), pinner, "s-1")
+ require.NoError(t, err)
+ require.Empty(t, got, "no pin means no live sandbox; callers must skip")
+}
+
+func TestSandboxConfigForExecutionUsesSentinelForGlobalDefault(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+
+ got, err := sandboxConfigForExecution(context.Background(), pinner, "s-1", "")
+ require.NoError(t, err)
+ require.Equal(t, types.SandboxConfigIDGlobalDefault, got)
+}
+
+// Attachment staging can be the call that creates the session's first sandbox
+// (WriteSessionInputFile provisions on first write), so it must pin like
+// execution does - not follow a pin that does not exist yet.
+func TestSandboxConfigForExecutionPinsOnFirstStaging(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+
+ staged, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", staged)
+
+ // The execution that follows in the same turn must land on the same config.
+ executed, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")
+ require.NoError(t, err)
+ require.Equal(t, staged, executed)
+}
+
+// Most deployments run every session on the WEKNORA_SANDBOX_* default, whose
+// pin is the sentinel and whose manager is the injected process-wide one. That
+// must keep collecting artifacts: resolving the sentinel yields no per-config
+// manager, which is not the same as "this session has no sandbox".
+func TestArtifactSessionSourceKeepsDefaultBackendForSentinelPin(t *testing.T) {
+ t.Setenv("WEKNORA_SANDBOX_MODE", "cube")
+
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+ _, err := pinner.Pin(ctx, "s-1", types.SandboxConfigIDGlobalDefault)
+ require.NoError(t, err)
+
+ source := &fakeSandboxSource{}
+ collector := &ArtifactCollector{
+ source: source,
+ resolver: stubSandboxResolver{},
+ pinner: pinner,
+ fallbackMgr: &artifactFallbackManager{source: source},
+ }
+
+ got := collector.sessionSource(ctx, "s-1")
+ require.NotNil(t, got)
+ // Sentinel pins resolve to the deployment-wide manager, which may be a
+ // distinct object from c.source even though both read the same backend.
+ _, ok := got.(SandboxArtifactSource)
+ require.True(t, ok)
+}
+
+// Attachment staging is reached through a runtime type assertion in
+// session_agent_qa.go, so a signature drift there does not fail the build - it
+// makes every agent turn error out with "does not support session attachment
+// staging". This pins the shape that call site asserts.
+func TestAgentServiceSatisfiesStagingAssertion(t *testing.T) {
+ var svc any = &agentService{}
+ _, ok := svc.(sessionAttachmentStager)
+ require.True(t, ok)
+}
+
+// An unpinned session has no live sandbox, so there is nothing to read even
+// though a process-wide source exists.
+func TestArtifactSessionSourceSkipsUnpinnedSession(t *testing.T) {
+ collector := &ArtifactCollector{
+ source: &fakeSandboxSource{},
+ resolver: stubSandboxResolver{},
+ pinner: NewSessionSandboxPinner(newPinTestDB(t)),
+ }
+
+ require.Nil(t, collector.sessionSource(context.Background(), "s-1"))
+}
diff --git a/internal/application/service/session_sandbox_gating_test.go b/internal/application/service/session_sandbox_gating_test.go
new file mode 100644
index 000000000..5c6b9494f
--- /dev/null
+++ b/internal/application/service/session_sandbox_gating_test.go
@@ -0,0 +1,62 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// A workspace can point an agent at a named Cube/E2B config while the
+// deployment default stays docker/local. In that combination the agent still
+// registers shell/skill tools against the remote sandbox (initializeSkillsManager
+// resolves the same per-config manager), so gating attachment staging on the
+// process-wide manager would leave those tools running against an empty
+// /workspace/input.
+func TestSessionSandboxInputStoreUsesNamedConfigNotDeploymentDefault(t *testing.T) {
+ t.Setenv("WEKNORA_SANDBOX_MODE", "local")
+
+ // The deployment default advertises no session filesystem, standing in for
+ // docker/local/disabled.
+ deploymentDefault := &stagingSandboxManager{
+ sandboxType: sandbox.SandboxTypeLocal,
+ disableFiles: true,
+ }
+ // The workspace's named config does advertise one.
+ named := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeCube}
+
+ svc := &agentService{
+ sandboxMgr: deploymentDefault,
+ sandboxResolver: stubSandboxResolver{mgr: named},
+ sandboxPinner: NewSessionSandboxPinner(newPinTestDB(t)),
+ }
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+
+ store, err := svc.sessionSandboxInputStore(ctx, "s-1", "cfg-remote")
+ require.NoError(t, err)
+ require.NotNil(t, store, "named remote config must still stage attachments")
+}
+
+// The mirror case: no named config means the deployment default decides, and a
+// backend without a session filesystem must not stage anything.
+func TestSessionSandboxInputStoreSkipsWhenDeploymentDefaultHasNoFilesystem(t *testing.T) {
+ t.Setenv("WEKNORA_SANDBOX_MODE", "local")
+
+ deploymentDefault := &stagingSandboxManager{
+ sandboxType: sandbox.SandboxTypeLocal,
+ disableFiles: true,
+ }
+ svc := &agentService{
+ sandboxMgr: deploymentDefault,
+ sandboxResolver: stubSandboxResolver{},
+ sandboxPinner: NewSessionSandboxPinner(newPinTestDB(t)),
+ }
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+
+ store, err := svc.sessionSandboxInputStore(ctx, "s-1", "")
+ require.NoError(t, err)
+ require.Nil(t, store)
+}
diff --git a/internal/application/service/session_sandbox_pin.go b/internal/application/service/session_sandbox_pin.go
new file mode 100644
index 000000000..e6712e93e
--- /dev/null
+++ b/internal/application/service/session_sandbox_pin.go
@@ -0,0 +1,178 @@
+// Package service: session -> sandbox config pin.
+//
+// A session's remote sandbox is long-lived (created with onTimeout=pause, so
+// its TTL pauses rather than destroys it), while the operations around it -
+// skill execution, attachment upload, artifact collection, teardown - each
+// resolve a backend independently at different points in time.
+//
+// If those points read "whichever config the agent points at right now", an
+// admin re-pointing an agent mid-conversation would make artifact collection
+// query the wrong account (artifacts silently vanish) and teardown fail
+// (a paused sandbox nobody knows the ID of, billing forever).
+//
+// The pin records which config the session's CURRENT sandbox lives on. It is
+// deliberately ephemeral: sessions outlive sandboxes by months, so a permanent
+// pin would make "nothing references this config" never become true.
+package service
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// SessionSandboxPinner is the only place session sandbox pins are read or
+// written. Centralising it is what keeps the four entry points consistent.
+type SessionSandboxPinner struct {
+ db *gorm.DB
+}
+
+// NewSessionSandboxPinner returns a pinner over the sessions table.
+func NewSessionSandboxPinner(db *gorm.DB) *SessionSandboxPinner {
+ return &SessionSandboxPinner{db: db}
+}
+
+// Read returns the pinned config ID, or "" when the session has no live
+// sandbox. Note the pin is an optimistic hint: the sandbox may have been
+// reclaimed out of band (see Clear).
+func (p *SessionSandboxPinner) Read(ctx context.Context, sessionID string) (string, error) {
+ pinned, _, err := p.read(ctx, sessionID)
+ return pinned, err
+}
+
+// read additionally reports whether the session row exists at all, which Pin
+// needs and Read deliberately hides: a caller asking "does this session have a
+// live sandbox" gets the same "no" either way, but a caller that just created
+// a sandbox must not mistake a vanished session for a clean pin.
+//
+// Soft-deleted sessions count as absent — GORM scopes them out — which is what
+// we want, since deleting a session also destroys its sandbox.
+func (p *SessionSandboxPinner) read(ctx context.Context, sessionID string) (string, bool, error) {
+ var pinned sql.NullString
+ result := p.db.WithContext(ctx).
+ Model(&types.Session{}).
+ Where("id = ?", sessionID).
+ Select("sandbox_config_id").
+ Scan(&pinned)
+ if result.Error != nil {
+ return "", false, result.Error
+ }
+ if result.RowsAffected == 0 {
+ return "", false, nil
+ }
+ if !pinned.Valid {
+ return "", true, nil
+ }
+ return pinned.String, true, nil
+}
+
+// Pin claims the session for configID and returns the winning value.
+//
+// The conditional update is what makes concurrent first-sandbox creations
+// safe: losers adopt the winner's config instead of building a second sandbox
+// on a second backend.
+//
+// A missing or soft-deleted session is an error rather than an empty result.
+// Pin is called just after a sandbox was created, so answering "" — which
+// means "no live sandbox" everywhere else — would hide a real sandbox whose
+// backend nobody recorded, leaving the orphan reaper as the only way back.
+func (p *SessionSandboxPinner) Pin(
+ ctx context.Context, sessionID, configID string,
+) (string, error) {
+ configID = strings.TrimSpace(configID)
+ if configID == "" {
+ configID = types.SandboxConfigIDGlobalDefault
+ }
+ // Two attempts: a concurrent Clear can hand the row back unpinned between
+ // our update and our read, and returning that empty value would be the
+ // same silent lie as a missing session.
+ for attempt := 0; attempt < 2; attempt++ {
+ result := p.db.WithContext(ctx).
+ Model(&types.Session{}).
+ Where("id = ? AND (sandbox_config_id IS NULL OR sandbox_config_id = ?)",
+ sessionID, "").
+ Update("sandbox_config_id", configID)
+ if result.Error != nil {
+ return "", result.Error
+ }
+ if result.RowsAffected > 0 {
+ return configID, nil
+ }
+ pinned, found, err := p.read(ctx, sessionID)
+ if err != nil {
+ return "", err
+ }
+ if !found {
+ return "", fmt.Errorf(
+ "sandbox: pin session %s to config %s: %w",
+ sessionID, configID, gorm.ErrRecordNotFound)
+ }
+ if pinned != "" {
+ // Someone else pinned first; adopt their choice.
+ return pinned, nil
+ }
+ }
+ return "", fmt.Errorf(
+ "sandbox: pin session %s to config %s: lost the claim race twice",
+ sessionID, configID)
+}
+
+// Clear releases the pin once the sandbox is gone, so the session's next
+// sandbox follows its agent's current backend choice.
+//
+// Best effort by nature: when the reaper reclaims an orphan from the provider
+// side the binding is already gone, so there is nothing to map back to a
+// session and the pin is left stale. Readers must therefore treat a non-empty
+// pin as a hint, not a guarantee that the sandbox still exists.
+func (p *SessionSandboxPinner) Clear(ctx context.Context, sessionID string) error {
+ return p.db.WithContext(ctx).
+ Model(&types.Session{}).
+ Where("id = ?", sessionID).
+ Update("sandbox_config_id", nil).Error
+}
+
+// sandboxConfigForExecution decides which config a session's sandbox runs on.
+//
+// Skill execution and attachment staging can be the first operation that creates
+// a session sandbox, so they adopt an existing pin and otherwise claim the
+// agent's current choice. Later operations must follow the pin instead.
+func sandboxConfigForExecution(
+ ctx context.Context,
+ pinner *SessionSandboxPinner,
+ sessionID string,
+ agentConfigID string,
+) (string, error) {
+ if pinner == nil || strings.TrimSpace(sessionID) == "" {
+ return agentConfigID, nil
+ }
+ pinned, err := pinner.Read(ctx, sessionID)
+ if err != nil {
+ return "", err
+ }
+ if pinned != "" {
+ return pinned, nil
+ }
+ return pinner.Pin(ctx, sessionID, agentConfigID)
+}
+
+// sandboxConfigForExistingSandbox returns the config an already-created
+// sandbox lives on, or "" when the session has none.
+//
+// Artifact collection and teardown deliberately never consult the agent: the
+// agent's current choice may no longer describe the long-lived sandbox they are
+// acting on.
+func sandboxConfigForExistingSandbox(
+ ctx context.Context,
+ pinner *SessionSandboxPinner,
+ sessionID string,
+) (string, error) {
+ if pinner == nil || strings.TrimSpace(sessionID) == "" {
+ return "", nil
+ }
+ return pinner.Read(ctx, sessionID)
+}
diff --git a/internal/application/service/session_sandbox_pin_test.go b/internal/application/service/session_sandbox_pin_test.go
new file mode 100644
index 000000000..33163779a
--- /dev/null
+++ b/internal/application/service/session_sandbox_pin_test.go
@@ -0,0 +1,136 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func newPinTestDB(t *testing.T) *gorm.DB {
+ t.Helper()
+ db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.Migrator().DropTable(&types.Session{}))
+ require.NoError(t, db.AutoMigrate(&types.Session{}))
+ require.NoError(t, db.Model(&types.Session{}).Create(map[string]any{
+ "id": "s-1",
+ "tenant_id": uint64(7),
+ }).Error)
+ return db
+}
+
+func TestPinWritesWhenUnset(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+
+ got, err := pinner.Pin(ctx, "s-1", "cfg-a")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", got)
+
+ read, err := pinner.Read(ctx, "s-1")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", read)
+}
+
+// Two concurrent first-sandbox creations must converge on one config, or the
+// session would end up with two sandboxes on two backends.
+func TestPinIsIdempotentAndReturnsExistingWinner(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+
+ first, err := pinner.Pin(ctx, "s-1", "cfg-a")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", first)
+
+ second, err := pinner.Pin(ctx, "s-1", "cfg-b")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", second, "the first writer wins; later callers adopt it")
+}
+
+func TestPinNormalizesEmptyConfigToSentinel(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+
+ got, err := pinner.Pin(ctx, "s-1", "")
+ require.NoError(t, err)
+ require.Equal(t, types.SandboxConfigIDGlobalDefault, got)
+}
+
+// A padded ID must land in the column exactly as Read will compare it, or the
+// conditional claim would never recognise its own write.
+func TestPinTrimsConfigIDBeforeStoring(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+
+ got, err := pinner.Pin(ctx, "s-1", " cfg-a ")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", got)
+
+ read, err := pinner.Read(ctx, "s-1")
+ require.NoError(t, err)
+ require.Equal(t, "cfg-a", read)
+}
+
+// Pin runs right after a sandbox was created, so a vanished session must be an
+// error: "" would read as "no live sandbox" and abandon a real one.
+func TestPinFailsWhenSessionIsGone(t *testing.T) {
+ db := newPinTestDB(t)
+ pinner := NewSessionSandboxPinner(db)
+ ctx := context.Background()
+
+ _, err := pinner.Pin(ctx, "missing", "cfg-a")
+ require.ErrorIs(t, err, gorm.ErrRecordNotFound)
+
+ require.NoError(t, db.Delete(&types.Session{}, "id = ?", "s-1").Error)
+ _, err = pinner.Pin(ctx, "s-1", "cfg-a")
+ require.ErrorIs(t, err, gorm.ErrRecordNotFound,
+ "a soft-deleted session already had its sandbox destroyed")
+}
+
+// Read keeps the lenient contract: absent session and unpinned session are
+// both simply "no live sandbox".
+func TestReadReportsNoSandboxForMissingSession(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+
+ read, err := pinner.Read(context.Background(), "missing")
+ require.NoError(t, err)
+ require.Empty(t, read)
+}
+
+// The pin dies with the sandbox: after teardown the session must be free to
+// follow its agent's CURRENT backend choice.
+func TestClearReleasesPin(t *testing.T) {
+ pinner := NewSessionSandboxPinner(newPinTestDB(t))
+ ctx := context.Background()
+
+ _, err := pinner.Pin(ctx, "s-1", "cfg-a")
+ require.NoError(t, err)
+ require.NoError(t, pinner.Clear(ctx, "s-1"))
+
+ read, err := pinner.Read(ctx, "s-1")
+ require.NoError(t, err)
+ require.Empty(t, read)
+}
+
+// Session delete soft-deletes the row before any follow-up work. Destroy must
+// therefore read sandbox_config_id first; otherwise the pinner sees an absent
+// session and teardown resolves the wrong backend (T4 regression).
+func TestSoftDeleteHidesSandboxPin(t *testing.T) {
+ db := newPinTestDB(t)
+ pinner := NewSessionSandboxPinner(db)
+ ctx := context.Background()
+
+ _, err := pinner.Pin(ctx, "s-1", "cfg-a")
+ require.NoError(t, err)
+
+ require.NoError(t, db.Delete(&types.Session{}, "id = ?", "s-1").Error)
+
+ read, err := pinner.Read(ctx, "s-1")
+ require.NoError(t, err)
+ require.Empty(t, read, "soft-deleted session must not expose its pin")
+}
diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.go
new file mode 100644
index 000000000..c95b81609
--- /dev/null
+++ b/internal/application/service/tenant_sandbox_config.go
@@ -0,0 +1,625 @@
+// Package service: sandbox backend config management.
+//
+// The load-bearing rule: some fields decide whether a config can still OPERATE
+// the sandboxes it already created. Overwriting them in place while sandboxes
+// are alive breaks those sandboxes in one of two ways, and both are bad enough
+// to refuse the save.
+//
+// Losing the control plane (provider, API URL, API key) means the new
+// credentials have no authority over the old sandboxes, so they can no longer be
+// listed or deleted. Session sandboxes are created with onTimeout=pause, so the
+// provider TTL never reclaims them either - the leak is permanent and it bills.
+// A paused sandbox is also what a session expects to RESUME, so conversations
+// break on top.
+//
+// Losing the data plane (E2B sandbox domain; Cube proxy URL and sandbox domain)
+// keeps cleanup possible, but every envd request now goes to the wrong host.
+// Every live session on this config fails at once - skill execution, attachment
+// staging, artifact collection - while the sandboxes stay alive and keep billing
+// until their sessions are deleted.
+//
+// Hence both groups are refused while sandboxes exist. The admin ends the owning
+// sessions or creates a second config and re-points agents; both keep the old
+// values intact, which is what keeps cleanup possible.
+package service
+
+import (
+ "context"
+ stderrors "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/utils"
+)
+
+const sandboxConfigCleanupTimeout = 20 * time.Second
+
+// SandboxIdentityChanged reports whether sandboxes already created under oldCfg
+// would stop being operable under newCfg. Names, templates, TTLs, HTTP timeouts
+// and env vars deliberately do not count: they only shape FUTURE sandboxes.
+//
+// newCfg must already have been merged with the stored config (see
+// types.MergeSandboxConfigForUpdate). The API masks secrets on read, so
+// comparing a raw payload would report a key rotation on every single save and
+// leave the config permanently uneditable.
+//
+// The comparison needs no deployment baseline: named configs inherit nothing, so
+// the stored fields are the whole identity. It is also deliberately free of
+// validation — see sandbox.IdentityOf for why an unreachable old endpoint must
+// still be judgeable.
+func SandboxIdentityChanged(oldCfg, newCfg *types.TenantSandboxConfig) bool {
+ if oldCfg == nil {
+ // Nothing exists yet, so nothing can be stranded.
+ return false
+ }
+ if newCfg == nil {
+ return true
+ }
+ return sandbox.IdentityOf(oldCfg) != sandbox.IdentityOf(newCfg)
+}
+
+// ErrSandboxesStillLive is returned when an identity change or deletion is
+// refused because the current credentials still own provider resources.
+var ErrSandboxesStillLive = stderrors.New("sandbox config still owns live sandboxes")
+
+// SandboxesStillLiveError carries the provider inventory the handler must show
+// in its 409 response; recomputing it could race and disagree with the refusal.
+type SandboxesStillLiveError struct {
+ Inventory SandboxInventory
+}
+
+func (e *SandboxesStillLiveError) Error() string {
+ return fmt.Sprintf("%s: %d", ErrSandboxesStillLive, e.Inventory.SandboxCount)
+}
+
+func (e *SandboxesStillLiveError) Unwrap() error {
+ return ErrSandboxesStillLive
+}
+
+// ErrSandboxInventoryUnverifiable is returned when the provider cannot be
+// reached to answer "does this config still own sandboxes?".
+//
+// It is deliberately distinct from ErrSandboxesStillLive: one means "there ARE
+// sandboxes, deal with them", the other means "we cannot tell". The second is
+// the only case a force delete may override, because an endpoint whose DNS
+// record is gone would otherwise make its config permanently undeletable.
+var ErrSandboxInventoryUnverifiable = stderrors.New(
+ "cannot verify whether the sandbox config still owns sandboxes")
+
+// ErrSandboxConfigNameRequired is a sentinel so transports can classify this as
+// bad input without matching on the message text.
+var ErrSandboxConfigNameRequired = stderrors.New("sandbox config name is required")
+
+// ErrNamedSandboxBackendUnsupported marks a sandbox type that cannot be stored
+// as a user-facing named backend config.
+var ErrNamedSandboxBackendUnsupported = stderrors.New(
+ "named sandbox configs only support cube and e2b backends",
+)
+
+// SandboxInventory describes what a config holds and who a change disturbs.
+type SandboxInventory struct {
+ SandboxCount int `json:"sandbox_count"`
+ SessionIDs []string `json:"session_ids,omitempty"`
+ AgentNames []string `json:"agent_names,omitempty"`
+
+ // Unverifiable reports that SandboxCount is unknown rather than zero
+ // because the provider could not be reached. The management page must say
+ // so instead of rendering a reassuring "0 sandboxes".
+ Unverifiable bool `json:"unverifiable,omitempty"`
+}
+
+// CreateSandboxConfigInput is the create payload.
+type CreateSandboxConfigInput struct {
+ Name string
+ Description string
+ Config *types.TenantSandboxConfig
+}
+
+// UpdateSandboxConfigInput is the update payload. Config may carry redacted
+// placeholders that resolve against the stored row.
+type UpdateSandboxConfigInput struct {
+ Name string
+ Description string
+ Config *types.TenantSandboxConfig
+}
+
+// SandboxConfigAgentRepo is the slice of the agent repository this service
+// needs. Agent references are warnings, never grounds for refusing a change.
+type SandboxConfigAgentRepo interface {
+ ListNamesBySandboxConfigID(ctx context.Context, tenantID uint64, configID string) ([]string, error)
+}
+
+// TenantSandboxConfigService owns the sandbox config lifecycle.
+type TenantSandboxConfigService struct {
+ repo repository.TenantSandboxConfigRepository
+ agents SandboxConfigAgentRepo
+ globalCfg *sandbox.Config
+ now func() time.Time
+
+ // newClient is injectable so tests can supply a provider inventory.
+ newClient func(*sandbox.Config) (sandbox.ConfigSandboxClient, error)
+}
+
+// NewTenantSandboxConfigService wires the config service.
+func NewTenantSandboxConfigService(
+ repo repository.TenantSandboxConfigRepository,
+ agents SandboxConfigAgentRepo,
+ globalCfg *sandbox.Config,
+) *TenantSandboxConfigService {
+ return &TenantSandboxConfigService{
+ repo: repo,
+ agents: agents,
+ globalCfg: globalCfg,
+ now: time.Now,
+ newClient: func(cfg *sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ return sandbox.NewRemoteClientForCheck(cfg)
+ },
+ }
+}
+
+// SanitizeSandboxConfig resolves redacted secrets and validates the payload
+// before it can be persisted.
+func SanitizeSandboxConfig(
+ incoming, existing *types.TenantSandboxConfig,
+) (*types.TenantSandboxConfig, error) {
+ if incoming == nil {
+ return nil, nil
+ }
+ merged := types.MergeSandboxConfigForUpdate(incoming, existing)
+
+ if merged.SandboxType != "" {
+ if _, err := sandbox.ParseSandboxType(merged.SandboxType); err != nil {
+ return nil, err
+ }
+ }
+ for _, endpoint := range sandboxConfigEndpoints(merged) {
+ if err := sandbox.ValidateOutboundURL(endpoint); err != nil {
+ return nil, err
+ }
+ }
+ // Without an AES key the Value() hook would persist these secrets in
+ // plaintext. Refuse instead of silently downgrading storage security.
+ if sandboxConfigHasSecrets(merged) && utils.GetAESKey() == nil {
+ return nil, apperrors.NewBadRequestError(
+ "SYSTEM_AES_KEY is not configured; refusing to store sandbox credentials in plaintext",
+ )
+ }
+ // Reject an incomplete config here rather than at first sandbox allocation.
+ // Resolving is what the runtime does, so both paths agree by construction.
+ // The baseline passed in is irrelevant to the outcome: named configs inherit
+ // no provider field, so only merged decides what is missing.
+ // Returned unwrapped so respondSandboxConfigServiceError can classify the
+ // sentinel; wrapping it in an AppError here would hide the chain.
+ if _, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DefaultConfig()); err != nil {
+ return nil, err
+ }
+ return merged, nil
+}
+
+func validateNamedSandboxBackend(cfg *types.TenantSandboxConfig) error {
+ if cfg == nil || strings.TrimSpace(cfg.SandboxType) == "" {
+ return apperrors.NewBadRequestError("sandbox backend type is required")
+ }
+ if !sandbox.IsNamedSandboxBackendType(cfg.SandboxType) {
+ return fmt.Errorf("%w", ErrNamedSandboxBackendUnsupported)
+ }
+ return nil
+}
+
+func filterPublicSandboxConfigs(
+ list []*types.TenantSandboxConfigEntity,
+) []*types.TenantSandboxConfigEntity {
+ if len(list) == 0 {
+ return list
+ }
+ out := make([]*types.TenantSandboxConfigEntity, 0, len(list))
+ for _, e := range list {
+ if types.IsSandboxWorkspacePolicyRow(e) {
+ continue
+ }
+ out = append(out, e)
+ }
+ return out
+}
+
+func findWorkspacePolicyRow(
+ list []*types.TenantSandboxConfigEntity,
+) *types.TenantSandboxConfigEntity {
+ for _, e := range list {
+ if types.IsSandboxWorkspacePolicyRow(e) {
+ return e
+ }
+ }
+ return nil
+}
+
+// WorkspaceScriptsDisabled reports whether agents that rely on the deployment
+// default (empty sandbox_config_id) must not execute skill scripts.
+func (s *TenantSandboxConfigService) WorkspaceScriptsDisabled(
+ ctx context.Context, tenantID uint64,
+) (bool, error) {
+ list, err := s.repo.ListByTenant(ctx, tenantID)
+ if err != nil {
+ return false, err
+ }
+ return findWorkspacePolicyRow(list) != nil, nil
+}
+
+// SetWorkspaceScriptsDisabled toggles workspace-level script execution for
+// agents that do not point at a named cube/e2b config.
+func (s *TenantSandboxConfigService) SetWorkspaceScriptsDisabled(
+ ctx context.Context, tenantID uint64, disabled bool,
+) error {
+ list, err := s.repo.ListByTenant(ctx, tenantID)
+ if err != nil {
+ return err
+ }
+ existing := findWorkspacePolicyRow(list)
+ if disabled {
+ if existing != nil {
+ return nil
+ }
+ entity := &types.TenantSandboxConfigEntity{
+ ID: uuid.New().String(),
+ TenantID: tenantID,
+ Name: types.SandboxWorkspacePolicyConfigName,
+ Description: "",
+ SandboxType: string(sandbox.SandboxTypeDisabled),
+ Config: &types.TenantSandboxConfig{SandboxType: string(sandbox.SandboxTypeDisabled)},
+ }
+ return s.repo.Create(ctx, entity)
+ }
+ if existing == nil {
+ return nil
+ }
+ return s.repo.SoftDelete(ctx, tenantID, existing.ID)
+}
+
+// Create stores a new config.
+func (s *TenantSandboxConfigService) Create(
+ ctx context.Context, tenantID uint64, in CreateSandboxConfigInput,
+) (*types.TenantSandboxConfigEntity, error) {
+ merged, err := SanitizeSandboxConfig(in.Config, nil)
+ if err != nil {
+ return nil, err
+ }
+ if err := validateNamedSandboxBackend(merged); err != nil {
+ return nil, err
+ }
+ name := strings.TrimSpace(in.Name)
+ if name == "" {
+ return nil, ErrSandboxConfigNameRequired
+ }
+ entity := &types.TenantSandboxConfigEntity{
+ ID: uuid.New().String(),
+ TenantID: tenantID,
+ Name: name,
+ Description: in.Description,
+ Config: merged,
+ }
+ if merged != nil {
+ entity.SandboxType = merged.SandboxType
+ }
+ if err := s.repo.Create(ctx, entity); err != nil {
+ return nil, err
+ }
+ return entity, nil
+}
+
+// List returns the workspace's user-facing configs (policy row excluded).
+func (s *TenantSandboxConfigService) List(
+ ctx context.Context, tenantID uint64,
+) ([]*types.TenantSandboxConfigEntity, error) {
+ list, err := s.repo.ListByTenant(ctx, tenantID)
+ if err != nil {
+ return nil, err
+ }
+ return filterPublicSandboxConfigs(list), nil
+}
+
+// Get returns one config, or nil when absent.
+func (s *TenantSandboxConfigService) Get(
+ ctx context.Context, tenantID uint64, id string,
+) (*types.TenantSandboxConfigEntity, error) {
+ entity, err := s.repo.GetByID(ctx, tenantID, id)
+ if err != nil || entity == nil {
+ return nil, err
+ }
+ if types.IsSandboxWorkspacePolicyRow(entity) {
+ return nil, nil
+ }
+ return entity, nil
+}
+
+// Inventory answers what changing or deleting this config would disturb.
+//
+// An unreachable provider is reported through Unverifiable rather than as an
+// error: the management page still has to render the card, and the agent names
+// it warns about come from our own database.
+func (s *TenantSandboxConfigService) Inventory(
+ ctx context.Context, tenantID uint64, id string,
+) (SandboxInventory, error) {
+ entity, err := s.repo.GetByID(ctx, tenantID, id)
+ if err != nil {
+ return SandboxInventory{}, err
+ }
+ if entity == nil {
+ return SandboxInventory{}, apperrors.NewNotFoundError("sandbox config not found")
+ }
+ summaries, err := s.listSandboxes(ctx, entity.Config, tenantID, id)
+ inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
+ if err != nil {
+ logger.Warnf(ctx, "[sandbox] inventory of config %s is unverifiable: %v", id, err)
+ inv.Unverifiable = true
+ }
+ return inv, nil
+}
+
+// listSandboxes enumerates what the config currently owns. A nil client means
+// the backend holds no remote resources at all, which is a verified empty.
+func (s *TenantSandboxConfigService) listSandboxes(
+ ctx context.Context,
+ cfg *types.TenantSandboxConfig,
+ tenantID uint64,
+ id string,
+) ([]sandbox.RemoteSandboxSummary, error) {
+ client, err := s.clientFor(cfg)
+ if err != nil {
+ return nil, err
+ }
+ if client == nil {
+ return nil, nil
+ }
+ return sandbox.ListConfigSandboxes(ctx, client, tenantID, id)
+}
+
+// Update applies an edit. Identity edits are cordoned before inventory and
+// swept afterwards using the old client so credentials are never overwritten
+// while they still own provider resources.
+func (s *TenantSandboxConfigService) Update(
+ ctx context.Context, tenantID uint64, id string, in UpdateSandboxConfigInput,
+) (*types.TenantSandboxConfigEntity, error) {
+ entity, err := s.repo.GetByID(ctx, tenantID, id)
+ if err != nil || entity == nil {
+ return nil, err
+ }
+ if types.IsSandboxWorkspacePolicyRow(entity) {
+ return nil, apperrors.NewBadRequestError("workspace policy cannot be edited here")
+ }
+ merged, err := SanitizeSandboxConfig(in.Config, entity.Config)
+ if err != nil {
+ return nil, err
+ }
+ if err := validateNamedSandboxBackend(merged); err != nil {
+ return nil, err
+ }
+ if !SandboxIdentityChanged(entity.Config, merged) {
+ return s.writeConfig(ctx, entity, in, merged)
+ }
+
+ if err := s.repo.SetCordon(ctx, tenantID, id, s.now()); err != nil {
+ return nil, err
+ }
+ defer s.clearCordonAfterRequest(ctx, tenantID, id)
+
+ // When old credentials no longer reach the provider we cannot enumerate
+ // sandboxes to refuse the edit — but blocking the save traps the admin on
+ // a key they are trying to fix. Proceed and skip the post-write sweep;
+ // sandboxes we cannot see may become orphans and need provider-side cleanup.
+ oldClient, err := s.clientFor(entity.Config)
+ if err != nil {
+ logger.Warnf(ctx,
+ "[sandbox] config %s: old credentials unusable for inventory: %v; proceeding",
+ id, err)
+ oldClient = nil
+ }
+ if oldClient != nil {
+ summaries, listErr := sandbox.ListConfigSandboxes(ctx, oldClient, tenantID, id)
+ if listErr != nil {
+ logger.Warnf(ctx,
+ "[sandbox] config %s: cannot verify sandbox inventory with old credentials: %v; proceeding",
+ id, listErr)
+ oldClient = nil
+ } else if len(summaries) > 0 {
+ inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
+ return nil, &SandboxesStillLiveError{Inventory: inv}
+ }
+ }
+
+ updated, err := s.writeConfig(ctx, entity, in, merged)
+ if err != nil {
+ return nil, err
+ }
+
+ if oldClient != nil {
+ s.sweepAfterWrite(ctx, oldClient, tenantID, id)
+ }
+ return updated, nil
+}
+
+// Delete refuses only while the config still owns sandboxes. Agent references
+// are permanent state and are surfaced as warnings by callers, not blockers.
+//
+// force covers exactly one case: the provider could not be reached, so we cannot
+// tell whether anything is live. Without it a config whose endpoint's DNS record
+// disappeared could never be removed — unlike an edit, deletion has no "create a
+// second config" way out. It does NOT override sandboxes we can actually see;
+// those still have to be dealt with through their sessions, otherwise the forced
+// deletion would be precisely the permanent leak this whole flow prevents.
+func (s *TenantSandboxConfigService) Delete(
+ ctx context.Context, tenantID uint64, id string, force bool,
+) error {
+ entity, err := s.repo.GetByID(ctx, tenantID, id)
+ if err != nil {
+ return err
+ }
+ // Reporting success for a config that is not there would let the UI drop a
+ // card the workspace still has, so absence is an explicit 404.
+ if entity == nil {
+ return apperrors.NewNotFoundError("sandbox config not found")
+ }
+ if types.IsSandboxWorkspacePolicyRow(entity) {
+ return apperrors.NewBadRequestError("workspace policy cannot be deleted here")
+ }
+ summaries, listErr := s.listSandboxes(ctx, entity.Config, tenantID, id)
+ if listErr != nil {
+ if !force {
+ return fmt.Errorf("%w: %v", ErrSandboxInventoryUnverifiable, listErr)
+ }
+ logger.Warnf(ctx,
+ "[sandbox] force-deleting config %s without verifying its sandboxes: %v",
+ id, listErr)
+ }
+ if len(summaries) > 0 {
+ inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
+ return &SandboxesStillLiveError{Inventory: inv}
+ }
+ return s.repo.SoftDelete(ctx, tenantID, id)
+}
+
+func (s *TenantSandboxConfigService) clientFor(
+ cfg *types.TenantSandboxConfig,
+) (sandbox.ConfigSandboxClient, error) {
+ // The baseline only supplies the deployment's execution timeout; every
+ // provider field comes from cfg, so a nil globalCfg cannot change which
+ // backend this client talks to.
+ base := s.globalCfg
+ if base == nil {
+ base = sandbox.DefaultConfig()
+ }
+ effective, err := sandbox.ResolveEffectiveConfig(cfg, base)
+ if err != nil {
+ return nil, err
+ }
+ switch effective.Type {
+ case sandbox.SandboxTypeCube, sandbox.SandboxTypeE2B:
+ return s.newClient(effective)
+ default:
+ return nil, nil
+ }
+}
+
+func (s *TenantSandboxConfigService) writeConfig(
+ ctx context.Context,
+ entity *types.TenantSandboxConfigEntity,
+ in UpdateSandboxConfigInput,
+ merged *types.TenantSandboxConfig,
+) (*types.TenantSandboxConfigEntity, error) {
+ if name := strings.TrimSpace(in.Name); name != "" {
+ entity.Name = name
+ }
+ entity.Description = in.Description
+ entity.Config = merged
+ if merged != nil {
+ entity.SandboxType = merged.SandboxType
+ }
+ if err := s.repo.Update(ctx, entity); err != nil {
+ return nil, err
+ }
+ return entity, nil
+}
+
+func (s *TenantSandboxConfigService) inventoryFromSummaries(
+ ctx context.Context,
+ tenantID uint64,
+ id string,
+ summaries []sandbox.RemoteSandboxSummary,
+) SandboxInventory {
+ inv := SandboxInventory{SandboxCount: len(summaries)}
+ for _, summary := range summaries {
+ if sessionID := summary.Metadata[sandbox.MetadataSessionIDKey()]; sessionID != "" {
+ inv.SessionIDs = append(inv.SessionIDs, sessionID)
+ }
+ }
+ if s.agents == nil {
+ return inv
+ }
+ names, err := s.agents.ListNamesBySandboxConfigID(ctx, tenantID, id)
+ if err != nil {
+ logger.Warnf(ctx, "[sandbox] list agents for config %s: %v", id, err)
+ return inv
+ }
+ inv.AgentNames = names
+ return inv
+}
+
+func (s *TenantSandboxConfigService) clearCordonAfterRequest(
+ ctx context.Context,
+ tenantID uint64,
+ id string,
+) {
+ cleanupCtx, cancel := context.WithTimeout(
+ context.WithoutCancel(ctx), sandboxConfigCleanupTimeout)
+ defer cancel()
+ if err := s.repo.ClearCordon(cleanupCtx, tenantID, id); err != nil {
+ logger.Warnf(ctx, "[sandbox] clear cordon on config %s: %v", id, err)
+ }
+}
+
+func (s *TenantSandboxConfigService) sweepAfterWrite(
+ ctx context.Context,
+ oldClient sandbox.ConfigSandboxClient,
+ tenantID uint64,
+ id string,
+) {
+ cleanupCtx, cancel := context.WithTimeout(
+ context.WithoutCancel(ctx), sandboxConfigCleanupTimeout)
+ defer cancel()
+ deleted, err := sandbox.ReleaseConfigSandboxes(cleanupCtx, oldClient, tenantID, id)
+ if err != nil {
+ logger.Warnf(ctx, "[sandbox] post-write sweep of config %s failed: %v", id, err)
+ return
+ }
+ if deleted > 0 {
+ logger.Infof(ctx,
+ "[sandbox] swept %d sandbox(es) created during the cordon window on config %s",
+ deleted, id)
+ }
+}
+
+// sandboxConfigEndpoints returns every non-empty tenant-supplied URL.
+func sandboxConfigEndpoints(cfg *types.TenantSandboxConfig) []string {
+ if cfg == nil {
+ return nil
+ }
+ var endpoints []string
+ if cfg.Cube != nil {
+ for _, raw := range []string{cfg.Cube.APIURL, cfg.Cube.ProxyURL} {
+ if raw != "" {
+ endpoints = append(endpoints, raw)
+ }
+ }
+ }
+ if cfg.E2B != nil && cfg.E2B.APIURL != "" {
+ endpoints = append(endpoints, cfg.E2B.APIURL)
+ }
+ return endpoints
+}
+
+// sandboxConfigHasSecrets reports whether cfg carries any value that must be
+// encrypted at rest.
+func sandboxConfigHasSecrets(cfg *types.TenantSandboxConfig) bool {
+ if cfg == nil {
+ return false
+ }
+ if cfg.Cube != nil && cfg.Cube.APIKey != "" {
+ return true
+ }
+ if cfg.E2B != nil && cfg.E2B.APIKey != "" {
+ return true
+ }
+ for _, value := range cfg.EnvVars {
+ if value != "" {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.go
new file mode 100644
index 000000000..b96aec545
--- /dev/null
+++ b/internal/application/service/tenant_sandbox_config_test.go
@@ -0,0 +1,757 @@
+package service
+
+import (
+ "context"
+ stderrors "errors"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// testGlobalSandboxConfig mirrors a deployment's WEKNORA_SANDBOX_* values. Named
+// configs inherit none of the provider fields from it; it is here so the service
+// under test is wired the way production wires it.
+func testGlobalSandboxConfig() *sandbox.Config {
+ cfg := sandbox.DefaultConfig()
+ cfg.Type = sandbox.SandboxTypeE2B
+ cfg.E2BAPIURL = "https://api.e2b.app"
+ cfg.E2BSandboxDomain = "e2b.app"
+ cfg.E2BAPIKey = "global-key"
+ cfg.E2BTemplate = "global-template"
+ return cfg
+}
+
+func e2bCfg(key, url, domain, template string, ttl int) *types.TenantSandboxConfig {
+ return &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIKey: key, APIURL: url, SandboxDomain: domain, TemplateID: template,
+ E2BSandboxTTLSeconds: ttl,
+ },
+ }
+}
+
+func cubeCfg(key, apiURL, proxyURL, domain string) *types.TenantSandboxConfig {
+ return &types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{
+ APIKey: key, APIURL: apiURL, ProxyURL: proxyURL, SandboxDomain: domain,
+ },
+ }
+}
+
+func TestSandboxIdentityChanged(t *testing.T) {
+ tests := []struct {
+ name string
+ old, new *types.TenantSandboxConfig
+ want bool
+ }{
+ // Control plane: losing these loses the ability to clean up, and the
+ // leak bills forever.
+ {
+ name: "api key rotation changes identity",
+ old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ new: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ want: true,
+ },
+ {
+ name: "endpoint change changes identity",
+ old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ new: e2bCfg("key-a", "https://self.hosted", "e2b.app", "t1", 300),
+ want: true,
+ },
+ {
+ name: "provider switch changes identity",
+ old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ new: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app"),
+ want: true,
+ },
+ // Data plane: the control plane still works so cleanup stays possible,
+ // but every envd request now goes to the wrong host, so every live
+ // session on this config fails at once.
+ {
+ name: "e2b sandbox domain change strands live sessions",
+ old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ new: e2bCfg("key-a", "https://api.e2b.app", "e2b.dev", "t1", 300),
+ want: true,
+ },
+ {
+ name: "cube proxy url change strands live sessions",
+ old: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app"),
+ new: cubeCfg("key-a", "https://cube.example.com", "https://proxy2.example.com", "cube.app"),
+ want: true,
+ },
+ {
+ name: "cube sandbox domain change strands live sessions",
+ old: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app"),
+ new: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube2.app"),
+ want: true,
+ },
+ // Not identity changes: these only shape FUTURE sandboxes, so refusing
+ // them would be pure friction.
+ {
+ name: "template change only affects future sandboxes",
+ old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t2", 300),
+ want: false,
+ },
+ {
+ name: "ttl change is not an identity change",
+ old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),
+ want: false,
+ },
+ {
+ // Nothing is inherited, so filling in an endpoint that was blank
+ // really does re-point the config at a different account.
+ name: "filling in a blank endpoint changes identity",
+ old: &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIKey: "key-a"},
+ },
+ new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 0),
+ want: true,
+ },
+ {
+ // Only the ACTIVE provider's fields describe where the sandboxes
+ // are; a leftover sub-struct from an earlier switch must not count.
+ name: "inactive provider fields are ignored",
+ old: &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIKey: "key-a"},
+ Cube: &types.CubeSandboxConfig{APIKey: "stale-a"},
+ },
+ new: &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIKey: "key-a"},
+ Cube: &types.CubeSandboxConfig{APIKey: "stale-b"},
+ },
+ want: false,
+ },
+ {
+ name: "no previous config means nothing to strand",
+ old: nil,
+ new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ want: false,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ require.Equal(t, tt.want, SandboxIdentityChanged(tt.old, tt.new))
+ })
+ }
+}
+
+// The UI never sends the real API key back - it echoes a mask. Comparing the
+// incoming payload directly would therefore report an identity change on EVERY
+// save and make the config permanently uneditable. This pins the required
+// ordering: merge first, judge second.
+func TestSandboxIdentityChangedAfterMaskMerge(t *testing.T) {
+ stored := e2bCfg("real-key", "https://api.e2b.app", "e2b.app", "t1", 300)
+ incoming := e2bCfg(types.RedactedSecretPlaceholder, "https://api.e2b.app", "e2b.app", "t1", 300)
+
+ merged := types.MergeSandboxConfigForUpdate(incoming, stored)
+
+ require.False(t,
+ SandboxIdentityChanged(stored, merged),
+ "a masked key that merges back to the stored one is not a rotation")
+}
+
+// An admin re-points a config precisely because its old endpoint died, so the
+// verdict must not depend on that endpoint being reachable or even resolvable.
+// Routing this through the SSRF-guarding resolver would lock the config down at
+// the worst possible moment.
+func TestSandboxIdentityChangedJudgesUnreachableOldEndpoint(t *testing.T) {
+ dead := cubeCfg("key-a", "https://decommissioned.invalid", "https://proxy.invalid", "cube.app")
+ live := cubeCfg("key-a", "https://cube.example.com", "https://proxy.invalid", "cube.app")
+
+ require.True(t, SandboxIdentityChanged(dead, live))
+ require.False(t, SandboxIdentityChanged(dead, dead))
+}
+
+// fakeConfigRepo records cordon transitions so tests can assert the sequence
+// that prevents old credentials from being overwritten while they still own
+// provider resources.
+type fakeConfigRepo struct {
+ entity *types.TenantSandboxConfigEntity
+ policy *types.TenantSandboxConfigEntity
+
+ events []string
+ updated *types.TenantSandboxConfigEntity
+ deleted bool
+
+ onSetCordon func()
+ onUpdate func()
+
+ clearCordonCtxErr error
+}
+
+func (f *fakeConfigRepo) Create(_ context.Context, e *types.TenantSandboxConfigEntity) error {
+ if types.IsSandboxWorkspacePolicyRow(e) {
+ f.policy = e
+ return nil
+ }
+ f.entity = e
+ return nil
+}
+
+func (f *fakeConfigRepo) GetByID(
+ _ context.Context, _ uint64, _ string,
+) (*types.TenantSandboxConfigEntity, error) {
+ f.events = append(f.events, "get")
+ return f.entity, nil
+}
+
+func (f *fakeConfigRepo) ListByTenant(
+ context.Context, uint64,
+) ([]*types.TenantSandboxConfigEntity, error) {
+ var out []*types.TenantSandboxConfigEntity
+ if f.entity != nil {
+ out = append(out, f.entity)
+ }
+ if f.policy != nil {
+ out = append(out, f.policy)
+ }
+ return out, nil
+}
+
+func (f *fakeConfigRepo) Update(
+ _ context.Context, e *types.TenantSandboxConfigEntity,
+) error {
+ f.events = append(f.events, "write")
+ f.updated = e
+ if f.onUpdate != nil {
+ f.onUpdate()
+ }
+ return nil
+}
+
+func (f *fakeConfigRepo) SoftDelete(_ context.Context, _ uint64, id string) error {
+ f.events = append(f.events, "delete")
+ if f.policy != nil && f.policy.ID == id {
+ f.policy = nil
+ }
+ f.deleted = true
+ return nil
+}
+
+func (f *fakeConfigRepo) SetCordon(_ context.Context, _ uint64, _ string, _ time.Time) error {
+ f.events = append(f.events, "cordon")
+ if f.onSetCordon != nil {
+ f.onSetCordon()
+ }
+ return nil
+}
+
+func (f *fakeConfigRepo) ClearCordon(ctx context.Context, _ uint64, _ string) error {
+ f.events = append(f.events, "uncordon")
+ f.clearCordonCtxErr = ctx.Err()
+ return nil
+}
+
+type stubAgentRepo struct {
+ names []string
+ err error
+}
+
+func (s stubAgentRepo) ListNamesBySandboxConfigID(
+ context.Context, uint64, string,
+) ([]string, error) {
+ return s.names, s.err
+}
+
+type stubProviderClient struct {
+ inventories [][]sandbox.RemoteSandboxSummary
+
+ listCalls int
+ deleted []string
+ deleteCtxErr error
+}
+
+func (s *stubProviderClient) List(
+ ctx context.Context, _ sandbox.RemoteListFilter,
+) ([]sandbox.RemoteSandboxSummary, error) {
+ s.listCalls++
+ if len(s.inventories) == 0 {
+ return nil, nil
+ }
+ idx := s.listCalls - 1
+ if idx >= len(s.inventories) {
+ idx = len(s.inventories) - 1
+ }
+ return s.inventories[idx], nil
+}
+
+func (s *stubProviderClient) Delete(ctx context.Context, sandboxID string) error {
+ s.deleted = append(s.deleted, sandboxID)
+ s.deleteCtxErr = ctx.Err()
+ return nil
+}
+
+func newTestConfigService(
+ t *testing.T,
+ repo *fakeConfigRepo,
+ client *stubProviderClient,
+ agents stubAgentRepo,
+) *TenantSandboxConfigService {
+ t.Helper()
+ if client == nil {
+ client = &stubProviderClient{}
+ }
+ svc := NewTenantSandboxConfigService(repo, agents, testGlobalSandboxConfig())
+ svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ return client, nil
+ }
+ return svc
+}
+
+// An identity change while sandboxes are alive must be refused, and the stored
+// credentials must remain untouched so cleanup stays possible.
+func TestUpdateRefusesIdentityChangeWhileSandboxesLive(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
+ {ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
+ }}}, stubAgentRepo{})
+
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ })
+
+ require.ErrorIs(t, err, ErrSandboxesStillLive)
+ require.Nil(t, repo.updated, "credentials must not be overwritten")
+ require.Equal(t, []string{"get", "cordon", "uncordon"}, repo.events,
+ "the cordon must be committed before the inventory check and released after")
+}
+
+// With no live sandboxes the write proceeds, and the cordon brackets it.
+func TestUpdateIdentityChangeCordonsThenWrites(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ })
+
+ require.NoError(t, err)
+ require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
+}
+
+// A non-identity edit must not pay for a cordon or a provider round-trip.
+func TestUpdateNonIdentityEditSkipsCordon(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ client := &stubProviderClient{}
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, client, stubAgentRepo{})
+
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod renamed",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),
+ })
+
+ require.NoError(t, err)
+ require.Equal(t, []string{"get", "write"}, repo.events)
+ require.Equal(t, "prod renamed", repo.updated.Name)
+ require.Equal(t, 0, client.listCalls)
+}
+
+func TestUpdateRefusalCarriesInventory(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
+ {ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
+ {ID: "sb-2", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-2"}},
+ }}}, stubAgentRepo{names: []string{"analyst", "writer"}})
+
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ })
+
+ var liveErr *SandboxesStillLiveError
+ require.ErrorAs(t, err, &liveErr)
+ require.Equal(t, 2, liveErr.Inventory.SandboxCount)
+ require.ElementsMatch(t, []string{"s-1", "s-2"}, liveErr.Inventory.SessionIDs)
+ require.Equal(t, []string{"analyst", "writer"}, liveErr.Inventory.AgentNames)
+}
+
+func TestUpdateSweepsSandboxCreatedDuringCordonWindow(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ ctx, cancel := context.WithCancel(context.Background())
+ client := &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{
+ nil,
+ {{ID: "sb-race", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-race"}}},
+ }}
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }, onUpdate: cancel}
+ svc := newTestConfigService(t, repo, client, stubAgentRepo{})
+
+ _, err := svc.Update(ctx, 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ })
+
+ require.NoError(t, err)
+ require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
+ require.Equal(t, []string{"sb-race"}, client.deleted)
+ require.NoError(t, client.deleteCtxErr, "post-write sweep must survive request cancellation")
+}
+
+func TestUpdateClearsCordonWhenRequestContextCancelled(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ ctx, cancel := context.WithCancel(context.Background())
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }, onSetCordon: cancel}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+
+ _, err := svc.Update(ctx, 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ })
+
+ require.NoError(t, err)
+ require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
+ require.NoError(t, repo.clearCordonCtxErr, "cordon release must survive request cancellation")
+}
+
+func TestDeleteRefusesWhileSandboxesLive(t *testing.T) {
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
+ {ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
+ }}}, stubAgentRepo{names: []string{"analyst"}})
+
+ err := svc.Delete(context.Background(), 7, "cfg-a", false)
+
+ require.ErrorIs(t, err, ErrSandboxesStillLive)
+ var liveErr *SandboxesStillLiveError
+ require.ErrorAs(t, err, &liveErr)
+ require.Equal(t, 1, liveErr.Inventory.SandboxCount)
+ require.Equal(t, []string{"s-1"}, liveErr.Inventory.SessionIDs)
+ require.Equal(t, []string{"analyst"}, liveErr.Inventory.AgentNames)
+ require.False(t, repo.deleted)
+ require.Equal(t, []string{"get"}, repo.events)
+}
+
+// "We cannot tell" must not read as "nothing there": refuse, and say which of
+// the two it is, because only this one is force-overridable.
+func TestDeleteRefusesWhenInventoryUnverifiable(t *testing.T) {
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+ svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ return nil, stderrors.New("dial tcp: no such host")
+ }
+
+ err := svc.Delete(context.Background(), 7, "cfg-a", false)
+
+ require.ErrorIs(t, err, ErrSandboxInventoryUnverifiable)
+ require.NotErrorIs(t, err, ErrSandboxesStillLive)
+ require.False(t, repo.deleted)
+}
+
+// Deletion has no "create a second config" way out, so a config whose endpoint
+// vanished must remain removable once an admin takes responsibility.
+func TestDeleteForceRemovesConfigWithUnverifiableInventory(t *testing.T) {
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+ svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ return nil, stderrors.New("dial tcp: no such host")
+ }
+
+ require.NoError(t, svc.Delete(context.Background(), 7, "cfg-a", true))
+ require.True(t, repo.deleted)
+}
+
+// force covers "cannot verify", never "verified live". Letting it through here
+// would strand paused sandboxes nobody can reach again - the exact leak this
+// whole flow exists to prevent.
+func TestDeleteForceStillRefusesVerifiedLiveSandboxes(t *testing.T) {
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
+ {ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
+ }}}, stubAgentRepo{})
+
+ err := svc.Delete(context.Background(), 7, "cfg-a", true)
+
+ require.ErrorIs(t, err, ErrSandboxesStillLive)
+ require.False(t, repo.deleted)
+}
+
+// The card still has to render, and the agent warning comes from our own DB, so
+// an unreachable provider is a flag rather than an error.
+func TestInventoryMarksUnverifiableInsteadOfFailing(t *testing.T) {
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{names: []string{"analyst"}})
+ svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ return nil, stderrors.New("dial tcp: no such host")
+ }
+
+ inv, err := svc.Inventory(context.Background(), 7, "cfg-a")
+
+ require.NoError(t, err)
+ require.True(t, inv.Unverifiable)
+ require.Zero(t, inv.SandboxCount)
+ require.Equal(t, []string{"analyst"}, inv.AgentNames)
+}
+
+// When old credentials cannot reach the provider, the update proceeds anyway
+// so the admin can fix a mistyped key; sandboxes_still_live still blocks when
+// the old credentials can list live instances.
+func TestUpdateProceedsWhenInventoryUnverifiable(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+ svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ return nil, stderrors.New("dial tcp: no such host")
+ }
+
+ updated, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ })
+
+ require.NoError(t, err)
+ require.NotNil(t, updated)
+ require.NotNil(t, repo.updated)
+ require.Equal(t, "key-b", repo.updated.Config.E2B.APIKey)
+ require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
+}
+
+func TestDeleteSoftDeletesWhenEmpty(t *testing.T) {
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
+ }}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+
+ err := svc.Delete(context.Background(), 7, "cfg-a", false)
+
+ require.NoError(t, err)
+ require.True(t, repo.deleted)
+ require.Equal(t, []string{"get", "delete"}, repo.events)
+}
+
+// Reporting success for a config that is not there would let the UI drop a card
+// the workspace still has, and hide a wrong ID from the caller.
+func TestDeleteAndInventoryReportMissingConfig(t *testing.T) {
+ repo := &fakeConfigRepo{}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+ ctx := context.Background()
+
+ err := svc.Delete(ctx, 7, "cfg-missing", false)
+ var appErr *apperrors.AppError
+ require.ErrorAs(t, err, &appErr)
+ require.Equal(t, http.StatusNotFound, appErr.HTTPCode)
+ require.False(t, repo.deleted)
+
+ _, err = svc.Inventory(ctx, 7, "cfg-missing")
+ require.ErrorAs(t, err, &appErr)
+ require.Equal(t, http.StatusNotFound, appErr.HTTPCode)
+}
+
+func TestSanitizeSandboxConfigPreservesRedactedSecret(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ existing := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIKey: "stored-key", APIURL: "https://203.0.113.10", TemplateID: "t1",
+ },
+ }
+ incoming := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIKey: types.RedactedSecretPlaceholder,
+ APIURL: "https://203.0.113.10",
+ TemplateID: "t1",
+ },
+ }
+
+ out, err := SanitizeSandboxConfig(incoming, existing)
+
+ require.NoError(t, err)
+ require.Equal(t, "stored-key", out.E2B.APIKey)
+}
+
+// Nothing is inherited from the deployment, so an incomplete config has to be
+// refused when it is saved rather than at the first sandbox allocation.
+func TestSanitizeSandboxConfigRejectsIncompleteConfig(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ incoming := &types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{APIURL: "https://203.0.113.10"},
+ }
+
+ _, err := SanitizeSandboxConfig(incoming, nil)
+
+ require.ErrorIs(t, err, sandbox.ErrSandboxConfigIncomplete)
+ require.Contains(t, err.Error(), "proxy_url")
+}
+
+// A masked key must still count as present: the merge restores it before the
+// completeness check runs, otherwise every edit of a saved config would be
+// rejected for a missing credential it never stopped having.
+func TestSanitizeSandboxConfigCountsRedactedSecretAsPresent(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ existing := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIKey: "stored-key", TemplateID: "t1"},
+ }
+ incoming := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIKey: types.RedactedSecretPlaceholder, TemplateID: "t2",
+ },
+ }
+
+ out, err := SanitizeSandboxConfig(incoming, existing)
+
+ require.NoError(t, err)
+ require.Equal(t, "t2", out.E2B.TemplateID)
+}
+
+func TestSanitizeSandboxConfigRejectsUnsafeURL(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ incoming := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIURL: "http://169.254.169.254"},
+ }
+
+ _, err := SanitizeSandboxConfig(incoming, nil)
+
+ require.ErrorIs(t, err, sandbox.ErrUnsafeOutboundURL)
+}
+
+func TestSanitizeSandboxConfigRejectsUnknownType(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ incoming := &types.TenantSandboxConfig{SandboxType: "quantum"}
+
+ _, err := SanitizeSandboxConfig(incoming, nil)
+
+ require.Error(t, err)
+}
+
+// Without an AES key the Value() hook would write these secrets as plaintext,
+// so saving must be refused rather than silently downgrading storage security.
+func TestSanitizeSandboxConfigRefusesSecretsWithoutAESKey(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", "")
+ incoming := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIKey: "plaintext-risk"},
+ }
+
+ _, err := SanitizeSandboxConfig(incoming, nil)
+
+ require.Error(t, err)
+
+ // A config without secrets is still allowed in that deployment.
+ _, err = SanitizeSandboxConfig(&types.TenantSandboxConfig{SandboxType: "local"}, nil)
+ require.NoError(t, err)
+}
+
+func TestSandboxesStillLiveErrorSupportsErrorsIs(t *testing.T) {
+ err := &SandboxesStillLiveError{Inventory: SandboxInventory{SandboxCount: 1}}
+
+ require.True(t, stderrors.Is(err, ErrSandboxesStillLive))
+}
+
+func TestCreateRejectsNonNamedSandboxBackend(t *testing.T) {
+ svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})
+
+ _, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{
+ Name: "local-dev",
+ Config: &types.TenantSandboxConfig{SandboxType: "local"},
+ })
+
+ require.ErrorIs(t, err, ErrNamedSandboxBackendUnsupported)
+}
+
+func TestWorkspaceScriptsDisabledPolicy(t *testing.T) {
+ repo := &fakeConfigRepo{}
+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
+ ctx := context.Background()
+
+ disabled, err := svc.WorkspaceScriptsDisabled(ctx, 7)
+ require.NoError(t, err)
+ require.False(t, disabled)
+
+ require.NoError(t, svc.SetWorkspaceScriptsDisabled(ctx, 7, true))
+ disabled, err = svc.WorkspaceScriptsDisabled(ctx, 7)
+ require.NoError(t, err)
+ require.True(t, disabled)
+
+ list, err := svc.List(ctx, 7)
+ require.NoError(t, err)
+ require.Empty(t, list)
+
+ require.NoError(t, svc.SetWorkspaceScriptsDisabled(ctx, 7, false))
+ disabled, err = svc.WorkspaceScriptsDisabled(ctx, 7)
+ require.NoError(t, err)
+ require.False(t, disabled)
+}
diff --git a/internal/application/service/tenant_sandbox_resolve.go b/internal/application/service/tenant_sandbox_resolve.go
new file mode 100644
index 000000000..a75961e18
--- /dev/null
+++ b/internal/application/service/tenant_sandbox_resolve.go
@@ -0,0 +1,124 @@
+// Package service - per-tenant sandbox resolution helpers.
+//
+// The sandbox package must not depend on repositories, so the config lookup is
+// adapted here and injected as sandbox.TenantSandboxConfigLoader.
+package service
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// tenantSandboxConfigLoader reads one named sandbox config for a workspace.
+type tenantSandboxConfigLoader struct {
+ repo repository.TenantSandboxConfigRepository
+ now func() time.Time
+}
+
+// NewTenantSandboxConfigLoader adapts the config repository onto the sandbox
+// package's loader contract.
+func NewTenantSandboxConfigLoader(
+ repo repository.TenantSandboxConfigRepository,
+) sandbox.TenantSandboxConfigLoader {
+ return &tenantSandboxConfigLoader{repo: repo, now: time.Now}
+}
+
+// Load reports whether the config exists and whether it is currently cordoned.
+// A cordon is honoured here - the single choke point every sandbox operation
+// passes through - so no new sandbox can be created on credentials that are
+// about to be replaced.
+func (l *tenantSandboxConfigLoader) Load(
+ ctx context.Context,
+ tenantID uint64,
+ configID string,
+) (sandbox.ResolvedTenantSandboxConfig, error) {
+ if l.repo == nil {
+ return sandbox.ResolvedTenantSandboxConfig{}, nil
+ }
+ entity, err := l.repo.GetByID(ctx, tenantID, configID)
+ if err != nil {
+ return sandbox.ResolvedTenantSandboxConfig{}, err
+ }
+ if entity == nil {
+ return sandbox.ResolvedTenantSandboxConfig{Found: false}, nil
+ }
+ return sandbox.ResolvedTenantSandboxConfig{
+ Config: entity.Config,
+ Found: true,
+ Cordoned: entity.IsCordoned(l.now(), types.SandboxCordonLease),
+ }, nil
+}
+
+// WorkspaceSandboxPolicy reports whether sandbox execution is disabled for the
+// entire workspace, including agents bound to named cube/e2b configs.
+type WorkspaceSandboxPolicy interface {
+ WorkspaceScriptsDisabled(ctx context.Context, tenantID uint64) (bool, error)
+}
+
+func deploymentSandboxDisabled() bool {
+ mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
+ return mode == "" || mode == "disabled"
+}
+
+// resolveTenantSandboxForConfig returns the Manager for an explicit config.
+//
+// Unlike the previous tenant-only helper this does NOT degrade to the default
+// manager on error: with several configs per workspace, a silent substitution
+// would run scripts on a different backend than the one selected - and then
+// artifact collection and sandbox teardown would target the wrong account.
+func resolveTenantSandboxForConfig(
+ ctx context.Context,
+ resolver sandbox.TenantSandboxResolver,
+ fallback sandbox.Manager,
+ tenantID uint64,
+ configID string,
+ policy WorkspaceSandboxPolicy,
+) (sandbox.Manager, error) {
+ // ① Deployment-wide kill switch (WEKNORA_SANDBOX_MODE empty/disabled).
+ if deploymentSandboxDisabled() {
+ return sandbox.NewDisabledManager(), nil
+ }
+
+ // ② Workspace kill switch — independent of resolver availability.
+ if policy != nil && tenantID != 0 {
+ disabled, err := policy.WorkspaceScriptsDisabled(ctx, tenantID)
+ if err != nil {
+ logger.Warnf(ctx,
+ "[sandbox] failed to read workspace sandbox policy for %d: %v",
+ tenantID, err)
+ } else if disabled {
+ return sandbox.NewDisabledManager(), nil
+ }
+ }
+
+ // ③ Default path: agents with no named config use the process-wide manager.
+ if configID == "" || configID == types.SandboxConfigIDGlobalDefault {
+ return fallback, nil
+ }
+
+ // ④ Named config: must not silently fall back to the deployment default.
+ if tenantID == 0 {
+ return nil, fmt.Errorf(
+ "sandbox: resolve config %q: missing workspace context", configID)
+ }
+ if resolver == nil {
+ return nil, fmt.Errorf(
+ "sandbox: resolve config %q: per-tenant resolver unavailable", configID)
+ }
+ mgr, err := resolver.Resolve(ctx, tenantID, configID)
+ if err != nil {
+ logger.Warnf(ctx,
+ "[sandbox] failed to resolve config %q for workspace %d: %v",
+ configID, tenantID, err)
+ return nil, err
+ }
+ return mgr, nil
+}
diff --git a/internal/common/redislock/token_lock.go b/internal/common/redislock/token_lock.go
new file mode 100644
index 000000000..18bb4b1f4
--- /dev/null
+++ b/internal/common/redislock/token_lock.go
@@ -0,0 +1,280 @@
+// Package redislock provides token-owned Redis locks with atomic renewal and
+// release. Callers must treat loss of ownership as loss of exclusive access.
+package redislock
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+const releaseTimeout = 5 * time.Second
+
+// ErrLockOwnershipLost means exclusive ownership can no longer be guaranteed.
+var ErrLockOwnershipLost = errors.New("redis lock ownership lost")
+
+type ownershipContextKey struct{}
+
+var (
+ releaseScript = redis.NewScript(`
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('DEL', KEYS[1])
+end
+return 0
+`)
+ renewScript = redis.NewScript(`
+if redis.call('GET', KEYS[1]) == ARGV[1] then
+ return redis.call('PEXPIRE', KEYS[1], ARGV[2])
+end
+return 0
+`)
+)
+
+// OwnershipContext returns a context that is canceled only when lock
+// ownership is lost, not when the request context is canceled. Outside a
+// renewable-lock callback it falls back to a cancellation-detached context.
+func OwnershipContext(ctx context.Context) context.Context {
+ if ctx == nil {
+ return context.Background()
+ }
+ if ownershipCtx, ok := ctx.Value(ownershipContextKey{}).(context.Context); ok {
+ return ownershipCtx
+ }
+ return context.WithoutCancel(ctx)
+}
+
+// NewToken returns a random owner token suitable for compare-and-* scripts.
+func NewToken() (string, error) {
+ var token [16]byte
+ if _, err := rand.Read(token[:]); err != nil {
+ return "", fmt.Errorf("generate redis lock token: %w", err)
+ }
+ return hex.EncodeToString(token[:]), nil
+}
+
+// TryAcquire attempts one SET NX acquisition.
+func TryAcquire(
+ ctx context.Context,
+ client redis.UniversalClient,
+ key string,
+ token string,
+ lease time.Duration,
+) (bool, error) {
+ if err := validateOperation(client, key, token, lease); err != nil {
+ return false, err
+ }
+ acquired, err := client.SetNX(ctx, key, token, lease).Result()
+ if err != nil {
+ return false, fmt.Errorf("acquire redis lock %q: %w", key, err)
+ }
+ return acquired, nil
+}
+
+// Acquire waits until the lock is acquired or ctx is cancelled.
+func Acquire(
+ ctx context.Context,
+ client redis.UniversalClient,
+ key string,
+ token string,
+ lease time.Duration,
+) error {
+ for {
+ acquired, err := TryAcquire(ctx, client, key, token, lease)
+ if err != nil {
+ return err
+ }
+ if acquired {
+ return nil
+ }
+
+ timer := time.NewTimer(retryDelay())
+ select {
+ case <-ctx.Done():
+ if !timer.Stop() {
+ <-timer.C
+ }
+ return ctx.Err()
+ case <-timer.C:
+ }
+ }
+}
+
+// Release deletes the lock only if token still owns it.
+func Release(
+ ctx context.Context,
+ client redis.UniversalClient,
+ key string,
+ token string,
+) (bool, error) {
+ if client == nil {
+ return false, errors.New("redis client is required")
+ }
+ if key == "" || token == "" {
+ return false, errors.New("redis lock key and token are required")
+ }
+ released, err := releaseScript.Run(ctx, client, []string{key}, token).Int64()
+ if err != nil {
+ return false, fmt.Errorf("release redis lock %q: %w", key, err)
+ }
+ return released != 0, nil
+}
+
+// Renew extends the lease only if token still owns the lock.
+func Renew(
+ ctx context.Context,
+ client redis.UniversalClient,
+ key string,
+ token string,
+ lease time.Duration,
+) (bool, error) {
+ if err := validateOperation(client, key, token, lease); err != nil {
+ return false, err
+ }
+ renewed, err := renewScript.Run(
+ ctx,
+ client,
+ []string{key},
+ token,
+ lease.Milliseconds(),
+ ).Int64()
+ if err != nil {
+ return false, fmt.Errorf("renew redis lock %q: %w", key, err)
+ }
+ return renewed != 0, nil
+}
+
+// WithRenewableLock acquires key, renews it while fn runs, and atomically
+// releases it on exit. Renewal failure cancels the context passed to fn.
+func WithRenewableLock(
+ ctx context.Context,
+ client redis.UniversalClient,
+ key string,
+ lease time.Duration,
+ renewInterval time.Duration,
+ fn func(context.Context) error,
+) (resultErr error) {
+ if fn == nil {
+ return errors.New("redis lock callback is required")
+ }
+ if renewInterval <= 0 || renewInterval >= lease {
+ return errors.New("redis lock renewal interval must be positive and shorter than the lease")
+ }
+
+ token, err := NewToken()
+ if err != nil {
+ return err
+ }
+ if err := Acquire(ctx, client, key, token, lease); err != nil {
+ return err
+ }
+
+ lockCtx, cancelLock := context.WithCancelCause(ctx)
+ ownershipCtx, cancelOwnership := context.WithCancelCause(context.Background())
+ lockCtx = context.WithValue(lockCtx, ownershipContextKey{}, ownershipCtx)
+ renewCtx, stopRenewal := context.WithCancel(context.WithoutCancel(ctx))
+ renewResult := make(chan error, 1)
+ go renewLoop(
+ renewCtx,
+ cancelLock,
+ cancelOwnership,
+ client,
+ key,
+ token,
+ lease,
+ renewInterval,
+ renewResult,
+ )
+
+ defer func() {
+ stopRenewal()
+ renewErr := <-renewResult
+ cancelLock(nil)
+ cancelOwnership(nil)
+
+ releaseCtx, cancelRelease := context.WithTimeout(context.Background(), releaseTimeout)
+ released, releaseErr := Release(releaseCtx, client, key, token)
+ cancelRelease()
+ if releaseErr == nil && !released && renewErr == nil {
+ releaseErr = fmt.Errorf("%w for %q", ErrLockOwnershipLost, key)
+ }
+
+ resultErr = errors.Join(resultErr, renewErr, ctx.Err(), releaseErr)
+ }()
+
+ resultErr = fn(lockCtx)
+ return resultErr
+}
+
+func renewLoop(
+ ctx context.Context,
+ cancelLock context.CancelCauseFunc,
+ cancelOwnership context.CancelCauseFunc,
+ client redis.UniversalClient,
+ key string,
+ token string,
+ lease time.Duration,
+ renewInterval time.Duration,
+ result chan<- error,
+) {
+ ticker := time.NewTicker(renewInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ result <- nil
+ return
+ case <-ticker.C:
+ renewed, err := Renew(ctx, client, key, token, lease)
+ if err != nil {
+ if errors.Is(err, context.Canceled) && ctx.Err() != nil {
+ result <- nil
+ return
+ }
+ ownershipErr := fmt.Errorf("%w: %w", ErrLockOwnershipLost, err)
+ cancelOwnership(ownershipErr)
+ cancelLock(ownershipErr)
+ result <- ownershipErr
+ return
+ }
+ if !renewed {
+ ownershipErr := fmt.Errorf("%w for %q", ErrLockOwnershipLost, key)
+ cancelOwnership(ownershipErr)
+ cancelLock(ownershipErr)
+ result <- ownershipErr
+ return
+ }
+ }
+ }
+}
+
+func validateOperation(
+ client redis.UniversalClient,
+ key string,
+ token string,
+ lease time.Duration,
+) error {
+ if client == nil {
+ return errors.New("redis client is required")
+ }
+ if key == "" || token == "" {
+ return errors.New("redis lock key and token are required")
+ }
+ if lease <= 0 {
+ return errors.New("redis lock lease must be positive")
+ }
+ return nil
+}
+
+func retryDelay() time.Duration {
+ var random [1]byte
+ if _, err := rand.Read(random[:]); err != nil {
+ return 50 * time.Millisecond
+ }
+ return 25*time.Millisecond + time.Duration(random[0])%50*time.Millisecond
+}
diff --git a/internal/common/redislock/token_lock_test.go b/internal/common/redislock/token_lock_test.go
new file mode 100644
index 000000000..50c47b390
--- /dev/null
+++ b/internal/common/redislock/token_lock_test.go
@@ -0,0 +1,237 @@
+package redislock_test
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/alicebob/miniredis/v2"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/common/redislock"
+)
+
+func newTokenLockTestClient(t *testing.T) (*redis.Client, *miniredis.Miniredis) {
+ t.Helper()
+
+ mini := miniredis.RunT(t)
+ client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
+ t.Cleanup(func() { require.NoError(t, client.Close()) })
+ return client, mini
+}
+
+func TestNewTokenReturnsUniqueOpaqueOwners(t *testing.T) {
+ t.Parallel()
+
+ first, err := redislock.NewToken()
+ require.NoError(t, err)
+ second, err := redislock.NewToken()
+ require.NoError(t, err)
+
+ require.Len(t, first, 32)
+ require.Len(t, second, 32)
+ require.NotEqual(t, first, second)
+}
+
+func TestTokenLockAcquireAndReleaseRequiresOwnership(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ ctx := context.Background()
+ key := "lock:ownership"
+
+ acquired, err := redislock.TryAcquire(ctx, client, key, "owner-a", time.Minute)
+ require.NoError(t, err)
+ require.True(t, acquired)
+
+ acquired, err = redislock.TryAcquire(ctx, client, key, "owner-b", time.Minute)
+ require.NoError(t, err)
+ require.False(t, acquired)
+
+ released, err := redislock.Release(ctx, client, key, "owner-b")
+ require.NoError(t, err)
+ require.False(t, released)
+ require.Equal(t, "owner-a", client.Get(ctx, key).Val())
+
+ released, err = redislock.Release(ctx, client, key, "owner-a")
+ require.NoError(t, err)
+ require.True(t, released)
+ require.ErrorIs(t, client.Get(ctx, key).Err(), redis.Nil)
+}
+
+func TestTokenLockRenewRequiresOwnership(t *testing.T) {
+ client, mini := newTokenLockTestClient(t)
+ ctx := context.Background()
+ key := "lock:renew"
+
+ require.NoError(t, client.Set(ctx, key, "owner-a", time.Second).Err())
+ renewed, err := redislock.Renew(ctx, client, key, "owner-b", time.Minute)
+ require.NoError(t, err)
+ require.False(t, renewed)
+
+ renewed, err = redislock.Renew(ctx, client, key, "owner-a", time.Minute)
+ require.NoError(t, err)
+ require.True(t, renewed)
+ mini.FastForward(2 * time.Second)
+ require.Equal(t, "owner-a", client.Get(ctx, key).Val())
+}
+
+func TestTokenLockRejectsUnsafeLeaseConfiguration(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ ctx := context.Background()
+
+ _, err := redislock.TryAcquire(ctx, client, "lock:key", "owner", 0)
+ require.Error(t, err)
+ _, err = redislock.Renew(ctx, client, "lock:key", "owner", -time.Second)
+ require.Error(t, err)
+ err = redislock.WithRenewableLock(
+ ctx,
+ client,
+ "lock:key",
+ time.Second,
+ time.Second,
+ func(context.Context) error { return nil },
+ )
+ require.Error(t, err)
+}
+
+func TestWithRenewableLockReturnsCallbackErrorAndReleases(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ ctx := context.Background()
+ key := "lock:callback"
+ want := errors.New("callback failed")
+
+ err := redislock.WithRenewableLock(
+ ctx,
+ client,
+ key,
+ time.Minute,
+ 20*time.Second,
+ func(context.Context) error { return want },
+ )
+
+ require.ErrorIs(t, err, want)
+ require.ErrorIs(t, client.Get(ctx, key).Err(), redis.Nil)
+}
+
+func TestWithRenewableLockHonorsContextWhileWaiting(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ ctx := context.Background()
+ key := "lock:busy"
+ require.NoError(t, client.Set(ctx, key, "owner-a", time.Minute).Err())
+
+ waitCtx, cancel := context.WithTimeout(ctx, 25*time.Millisecond)
+ defer cancel()
+ called := false
+ err := redislock.WithRenewableLock(
+ waitCtx,
+ client,
+ key,
+ time.Minute,
+ 20*time.Second,
+ func(context.Context) error {
+ called = true
+ return nil
+ },
+ )
+
+ require.ErrorIs(t, err, context.DeadlineExceeded)
+ require.False(t, called)
+}
+
+func TestWithRenewableLockCancelsCallbackAfterOwnershipLoss(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ key := "lock:lost"
+
+ err := redislock.WithRenewableLock(
+ context.Background(),
+ client,
+ key,
+ 100*time.Millisecond,
+ 10*time.Millisecond,
+ func(lockCtx context.Context) error {
+ require.NoError(t, client.Set(context.Background(), key, "replacement", time.Minute).Err())
+ select {
+ case <-lockCtx.Done():
+ return nil
+ case <-time.After(time.Second):
+ return errors.New("callback was not cancelled")
+ }
+ },
+ )
+
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "ownership lost")
+ require.Equal(t, "replacement", client.Get(context.Background(), key).Val())
+}
+
+func TestWithRenewableLockReportsOwnershipLossAtRelease(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ key := "lock:lost-before-renewal"
+
+ err := redislock.WithRenewableLock(
+ context.Background(),
+ client,
+ key,
+ time.Minute,
+ 20*time.Second,
+ func(context.Context) error {
+ return client.Set(context.Background(), key, "replacement", time.Minute).Err()
+ },
+ )
+
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "ownership lost")
+ require.Equal(t, "replacement", client.Get(context.Background(), key).Val())
+}
+
+func TestOwnershipContextSurvivesCallerCancellation(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ ctx, cancel := context.WithCancel(context.Background())
+
+ err := redislock.WithRenewableLock(
+ ctx,
+ client,
+ "lock:caller-cancel",
+ time.Minute,
+ 20*time.Second,
+ func(lockCtx context.Context) error {
+ ownershipCtx := redislock.OwnershipContext(lockCtx)
+ cancel()
+ require.ErrorIs(t, lockCtx.Err(), context.Canceled)
+ select {
+ case <-ownershipCtx.Done():
+ t.Fatal("caller cancellation must not imply lock ownership loss")
+ default:
+ }
+ return nil
+ },
+ )
+
+ require.ErrorIs(t, err, context.Canceled)
+}
+
+func TestOwnershipContextCancelsWhenRenewalLosesOwnership(t *testing.T) {
+ client, _ := newTokenLockTestClient(t)
+ key := "lock:ownership-context"
+
+ err := redislock.WithRenewableLock(
+ context.Background(),
+ client,
+ key,
+ 100*time.Millisecond,
+ 10*time.Millisecond,
+ func(lockCtx context.Context) error {
+ ownershipCtx := redislock.OwnershipContext(lockCtx)
+ require.NoError(t, client.Set(context.Background(), key, "replacement", time.Minute).Err())
+ select {
+ case <-ownershipCtx.Done():
+ return nil
+ case <-time.After(time.Second):
+ return errors.New("ownership context was not cancelled")
+ }
+ },
+ )
+
+ require.ErrorIs(t, err, redislock.ErrLockOwnershipLost)
+}
diff --git a/internal/container/container.go b/internal/container/container.go
index 4171f24fa..97bcac74e 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -161,6 +161,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewMCPServiceRepository))
must(container.Provide(repository.NewMCPToolApprovalRepository))
must(container.Provide(repository.NewMCPOAuthRepository))
+ must(container.Provide(repository.NewTenantSandboxConfigRepository))
must(container.Provide(repository.NewCustomAgentRepository))
must(container.Provide(repository.NewOrganizationRepository))
must(container.Provide(repository.NewKBShareRepository))
@@ -180,6 +181,19 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(mcp.NewMCPManager))
must(container.Provide(mcp.NewOAuthManager))
+ // Sandbox manager (script execution backend for skills). Reads
+ // WEKNORA_SANDBOX_MODE env var: "docker" | "local" | "cube" | "disabled"
+ // (default). The Cube mode wires a SessionBoundManager so each Session
+ // gets its own persistent MicroVM. See internal/sandbox/session_manager.go.
+ logger.Debugf(ctx, "[Container] Registering sandbox manager...")
+ must(container.Provide(newSandboxManager))
+ // Per-tenant sandbox backends: the resolver builds a manager per request
+ // from the tenant's own configuration, falling back to the singleton above
+ // for tenants that configured nothing.
+ must(container.Provide(service.NewTenantSandboxConfigLoader))
+ must(container.Provide(newTenantSandboxResolver))
+ must(container.Provide(newSandboxConfigDefaults))
+
// Business service layer
logger.Debugf(ctx, "[Container] Registering business services...")
must(container.Provide(service.NewTenantService))
@@ -202,6 +216,15 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewEvaluationService))
must(container.Provide(service.NewUserService))
must(container.Provide(service.NewSystemSettingService))
+ must(container.Provide(func(
+ repo repository.TenantSandboxConfigRepository,
+ agents interfaces.CustomAgentRepository,
+ ) *service.TenantSandboxConfigService {
+ return service.NewTenantSandboxConfigService(repo, agents, buildGlobalSandboxConfig())
+ }))
+ must(container.Provide(func(s *service.TenantSandboxConfigService) service.WorkspaceSandboxPolicy {
+ return s
+ }))
must(container.Provide(service.NewWeKnoraCloudService))
// Extract services - register individual extracters with names
@@ -256,6 +279,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
// SessionService is passed as parameter to CreateAgentEngine method when creating AgentService
logger.Debugf(ctx, "[Container] Registering event bus and agent service...")
must(container.Provide(event.NewEventBus))
+ must(container.Provide(service.NewSessionSandboxPinner))
must(container.Provide(func(cfg *config.Config, s interfaces.MCPToolApprovalService, rdb *redis.Client) *approval.Gate {
return approval.NewGate(cfg, &approval.Adapter{Svc: s}, rdb)
}))
@@ -268,6 +292,13 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering session service...")
must(container.Provide(service.NewSessionService))
+ // ArtifactCollector drains skill-generated files from the sandbox on
+ // each agent turn (see spec at
+ // docs/superpowers/specs/2026-07-10-skill-artifact-download-design.md).
+ // The factory returns nil when the sandbox backend does not support
+ // per-session file inspection; downstream code guards on nil.
+ must(container.Provide(service.NewArtifactCollectorFromSandboxManager))
+
logger.Debugf(ctx, "[Container] Registering task enqueuer...")
redisAvailable := os.Getenv("REDIS_ADDR") != ""
if redisAvailable {
@@ -352,6 +383,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewMessageHandler))
must(container.Provide(handler.NewMessageSuggestionHandler))
must(container.Provide(handler.NewModelHandler))
+ must(container.Provide(handler.NewSandboxConfigHandler))
must(container.Provide(handler.NewEvaluationHandler))
must(container.Provide(handler.NewInitializationHandler))
must(container.Provide(handler.NewAuthHandler))
diff --git a/internal/container/sandbox.go b/internal/container/sandbox.go
new file mode 100644
index 000000000..04a9f0980
--- /dev/null
+++ b/internal/container/sandbox.go
@@ -0,0 +1,294 @@
+// Package container - sandbox provider.
+//
+// This file wires up the sandbox.Manager singleton that gets injected into
+// agent_service and session_service. It is intentionally isolated from
+// container.go so environment-variable parsing and provider-specific
+// configuration stay out of the main provider table.
+package container
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/redis/go-redis/v9"
+ "gorm.io/gorm"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// newSandboxManager builds a sandbox.Manager from environment variables.
+// Recognised variables:
+//
+// WEKNORA_SANDBOX_MODE "docker" | "local" | "cube" | "e2b" | "disabled" (default "disabled")
+// WEKNORA_SANDBOX_TIMEOUT per-execute timeout in seconds (default 60)
+// WEKNORA_SANDBOX_DOCKER_IMAGE custom docker image (docker mode only)
+// WEKNORA_SANDBOX_REDIS_NAMESPACE Redis key namespace suffix (default derives from
+// WEKNORA_REDIS_NAMESPACE, then "weknora")
+// WEKNORA_SANDBOX_CUBE_API_URL CubeAPI endpoint (default http://127.0.0.1:33000)
+// WEKNORA_SANDBOX_CUBE_PROXY_URL CubeProxy endpoint (envd) (default http://127.0.0.1:80)
+// WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN sandbox routing domain (default cube.app)
+// WEKNORA_SANDBOX_CUBE_ENVD_PORT internal envd port (default 49983)
+// WEKNORA_SANDBOX_CUBE_API_KEY X-API-Key value (default empty; Cube auth disabled)
+// WEKNORA_SANDBOX_CUBE_TEMPLATE template ID (default tpl-2b7911a5c3bb419a8745957a)
+// WEKNORA_SANDBOX_CUBE_SANDBOX_TTL Cube-side sandbox timeout, seconds (default 1800)
+// WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT single HTTP call timeout, seconds (default 30)
+// WEKNORA_SANDBOX_E2B_API_KEY X-API-Key for the E2B backend (required for mode=e2b)
+// WEKNORA_SANDBOX_E2B_API_URL E2B control-plane endpoint (default https://api.e2b.app)
+// WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN sandbox routing domain (default e2b.app)
+// WEKNORA_SANDBOX_E2B_TEMPLATE template ID / alias
+// WEKNORA_SANDBOX_E2B_SANDBOX_TTL E2B-side idle timeout, seconds (default 300)
+// WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT single HTTP call timeout, seconds (default 30)
+func newSandboxManager(
+ redisClient *redis.Client,
+ sessionRepo interfaces.SessionRepository,
+) sandbox.Manager {
+ ctx := context.Background()
+
+ mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
+ if mode == "" {
+ mode = "disabled"
+ }
+
+ switch mode {
+ case "docker":
+ dockerImage := os.Getenv("WEKNORA_SANDBOX_DOCKER_IMAGE")
+ if dockerImage == "" {
+ dockerImage = sandbox.DefaultDockerImage
+ }
+ m, err := sandbox.NewManagerFromType("docker", true, dockerImage)
+ if err != nil {
+ logger.Warnf(ctx, "Failed to initialize Docker sandbox, falling back to disabled: %v", err)
+ return sandbox.NewDisabledManager()
+ }
+ logger.Infof(ctx, "Sandbox configured: mode=docker image=%s", dockerImage)
+ return m
+
+ case "local":
+ m, err := sandbox.NewManagerFromType("local", false, "")
+ if err != nil {
+ logger.Warnf(ctx, "Failed to initialize local sandbox: %v", err)
+ return sandbox.NewDisabledManager()
+ }
+ logger.Infof(ctx, "Sandbox configured: mode=local")
+ return m
+
+ case "cube":
+ return buildCubeManager(ctx, redisClient, sessionRepo)
+
+ case "e2b":
+ return buildE2BManager(ctx, redisClient, sessionRepo)
+
+ default:
+ logger.Infof(ctx, "Sandbox configured: mode=disabled")
+ return sandbox.NewDisabledManager()
+ }
+}
+
+func buildCubeManager(
+ ctx context.Context,
+ redisClient *redis.Client,
+ sessionRepo interfaces.SessionRepository,
+) sandbox.Manager {
+ cfg := sandbox.CubeConfigFromEnv()
+ // The pool lives as long as this process-wide manager, and its guarded
+ // dialer keeps the deployment default on the same outbound policy the
+ // per-tenant resolver enforces.
+ client, err := sandbox.NewCubeRemoteClientWithPool(cfg, sandbox.NewCubeTransportPool(nil))
+ if err != nil {
+ logger.Warnf(ctx, "Failed to build Cube sandbox client: %v (falling back to disabled)", err)
+ return sandbox.NewDisabledManager()
+ }
+ store, storeKind, err := selectSessionBindingStore(redisClient, true)
+ if err != nil {
+ logger.Errorf(ctx, "Refusing to start Cube sandbox: %v", err)
+ return sandbox.NewDisabledManager()
+ }
+ m, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{
+ Config: cfg,
+ Client: client,
+ Store: store,
+ Checker: sessionExistenceCheckerFor(sessionRepo),
+ })
+ if err != nil {
+ logger.Warnf(ctx, "Failed to initialize Cube sandbox: %v (falling back to disabled)", err)
+ return sandbox.NewDisabledManager()
+ }
+ logger.Infof(ctx,
+ "Sandbox configured: mode=cube api=%s proxy=%s domain=%s template=%s binding=%s",
+ cfg.CubeAPIURL, cfg.CubeProxyURL, cfg.CubeSandboxDomain, cfg.CubeTemplate, storeKind,
+ )
+ return m
+}
+
+func buildE2BManager(
+ ctx context.Context,
+ redisClient *redis.Client,
+ sessionRepo interfaces.SessionRepository,
+) sandbox.Manager {
+ cfg := sandbox.E2BConfigFromEnv()
+ client, err := sandbox.NewE2BRemoteClientWithTransport(cfg, sandbox.NewGuardedTransport())
+ if err != nil {
+ logger.Warnf(ctx, "Failed to build E2B sandbox client: %v (falling back to disabled)", err)
+ return sandbox.NewDisabledManager()
+ }
+ store, storeKind, err := selectSessionBindingStore(redisClient, true)
+ if err != nil {
+ logger.Errorf(ctx, "Refusing to start E2B sandbox: %v", err)
+ return sandbox.NewDisabledManager()
+ }
+ m, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{
+ Config: cfg,
+ Client: client,
+ Store: store,
+ Checker: sessionExistenceCheckerFor(sessionRepo),
+ })
+ if err != nil {
+ logger.Warnf(ctx, "Failed to initialize E2B sandbox: %v (falling back to disabled)", err)
+ return sandbox.NewDisabledManager()
+ }
+ logger.Infof(ctx,
+ "Sandbox configured: mode=e2b api=%s domain=%s template=%s ttl=%s binding=%s",
+ cfg.E2BAPIURL, cfg.E2BSandboxDomain, cfg.E2BTemplate, cfg.E2BSandboxTTL, storeKind,
+ )
+ return m
+}
+
+func selectSessionBindingStore(
+ redisClient *redis.Client,
+ requireRedis bool,
+) (sandbox.SessionSandboxBindingStore, string, error) {
+ namespace := strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_REDIS_NAMESPACE"))
+ if namespace == "" {
+ namespace = strings.TrimSpace(os.Getenv("WEKNORA_REDIS_NAMESPACE"))
+ }
+ if namespace == "" {
+ namespace = "weknora"
+ }
+ if redisClient != nil {
+ store, err := sandbox.NewRedisSessionSandboxBindingStore(redisClient, namespace)
+ if err != nil {
+ return nil, "", fmt.Errorf("build redis binding store: %w", err)
+ }
+ return store, "redis", nil
+ }
+ if requireRedis && !allowMemorySandboxBinding() {
+ return nil, "", errors.New(
+ "remote sandbox modes (cube/e2b) require Redis for session binding; " +
+ "set WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true only for single-instance dev",
+ )
+ }
+ logger.Warnf(context.Background(),
+ "[sandbox] No Redis configured, using in-memory binding store (single-instance)")
+ return sandbox.NewMemorySessionSandboxBindingStore(), "memory", nil
+}
+
+func allowMemorySandboxBinding() bool {
+ return strings.EqualFold(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING")), "true")
+}
+
+// sessionExistenceLookup is the narrow slice of SessionRepository the
+// session existence checker actually needs. Declaring it here (rather than
+// depending on interfaces.SessionRepository) keeps the checker easy to test
+// and lets the container inject a nil repository in Lite mode without
+// dragging the whole database contract along.
+type sessionExistenceLookup interface {
+ GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)
+}
+
+// sessionExistenceCheckerFor returns a SessionExistenceChecker backed by the
+// tenant session repository. When the repository is unavailable (Lite mode
+// without a database) the returned checker is permissive so single-process
+// deployments still work; multi-instance production paths always resolve a
+// real repository because the container refuses to boot without one.
+func sessionExistenceCheckerFor(
+ lookup sessionExistenceLookup,
+) sandbox.SessionExistenceChecker {
+ if lookup == nil {
+ return sandbox.PermissiveSessionExistenceChecker{}
+ }
+ return &repositorySessionExistenceChecker{lookup: lookup}
+}
+
+// repositorySessionExistenceChecker adapts SessionRepository.GetByID onto the
+// SessionExistenceChecker contract. gorm.ErrRecordNotFound → false, other
+// errors propagate so the lifecycle coordinator preserves bindings under
+// transient database failures.
+type repositorySessionExistenceChecker struct {
+ lookup sessionExistenceLookup
+}
+
+func (c *repositorySessionExistenceChecker) SessionExists(
+ ctx context.Context,
+ key sandbox.SessionSandboxKey,
+) (bool, error) {
+ if c == nil || c.lookup == nil {
+ return true, nil
+ }
+ session, err := c.lookup.GetByID(ctx, key.TenantID, key.SessionID)
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, apperrors.ErrSessionNotFound) {
+ return false, nil
+ }
+ return false, fmt.Errorf("session existence check: %w", err)
+ }
+ return session != nil, nil
+}
+
+// buildGlobalSandboxConfig returns the process-wide *sandbox.Config that
+// per-tenant overrides are merged onto.
+func buildGlobalSandboxConfig() *sandbox.Config {
+ return sandbox.DeploymentConfig()
+}
+
+// newSandboxConfigDefaults exposes the deployment's inheritable sandbox
+// defaults (secret-free) so the settings API can show what a workspace without
+// its own overrides actually runs on.
+func newSandboxConfigDefaults() *sandbox.ConfigDefaults {
+ return sandbox.DescribeDefaults(buildGlobalSandboxConfig())
+}
+
+// newTenantSandboxResolver wires the per-tenant resolver. The process-wide
+// manager remains the fallback for tenants that configured nothing, so
+// existing deployments are unaffected.
+func newTenantSandboxResolver(
+ defaultManager sandbox.Manager,
+ loader sandbox.TenantSandboxConfigLoader,
+ redisClient *redis.Client,
+ sessionRepo interfaces.SessionRepository,
+) sandbox.TenantSandboxResolver {
+ ctx := context.Background()
+
+ // Tenants may configure cube/e2b regardless of the global mode, so the
+ // resolver needs the same Redis-backed binding guarantees the global
+ // remote path demands. Without them per-tenant config stays disabled and
+ // every workspace keeps using the process-wide manager.
+ store, storeKind, err := selectSessionBindingStore(redisClient, true)
+ if err != nil {
+ logger.Warnf(ctx,
+ "Per-tenant sandbox config disabled: %v", err)
+ return nil
+ }
+ resolver, err := sandbox.NewTenantSandboxResolver(sandbox.TenantSandboxResolverDeps{
+ GlobalConfig: buildGlobalSandboxConfig(),
+ DefaultManager: defaultManager,
+ Loader: loader,
+ Store: store,
+ Checker: sessionExistenceCheckerFor(sessionRepo),
+ SharedTransport: sandbox.NewGuardedTransport(),
+ })
+ if err != nil {
+ logger.Warnf(ctx,
+ "Failed to initialize tenant sandbox resolver: %v "+
+ "(per-tenant sandbox config disabled)", err)
+ return nil
+ }
+ logger.Infof(ctx, "Tenant sandbox resolver configured: binding=%s", storeKind)
+ return resolver
+}
diff --git a/internal/container/sandbox_test.go b/internal/container/sandbox_test.go
new file mode 100644
index 000000000..c9e1952f4
--- /dev/null
+++ b/internal/container/sandbox_test.go
@@ -0,0 +1,104 @@
+package container
+
+import (
+ "context"
+ "errors"
+ "strconv"
+ "testing"
+
+ "github.com/alicebob/miniredis/v2"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func TestSelectSessionBindingStorePrefersRedis(t *testing.T) {
+ mini := miniredis.RunT(t)
+ client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
+ t.Cleanup(func() { _ = client.Close() })
+
+ store, kind, err := selectSessionBindingStore(client, true)
+ require.NoError(t, err)
+ require.Equal(t, "redis", kind)
+ require.IsType(t, &sandbox.RedisSessionSandboxBindingStore{}, store)
+}
+
+func TestSelectSessionBindingStoreRequiresRedisForRemoteModes(t *testing.T) {
+ _, _, err := selectSessionBindingStore(nil, true)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "require Redis")
+}
+
+func TestSelectSessionBindingStoreAllowsMemoryWhenOptedIn(t *testing.T) {
+ t.Setenv("WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING", "true")
+
+ store, kind, err := selectSessionBindingStore(nil, true)
+ require.NoError(t, err)
+ require.Equal(t, "memory", kind)
+ require.IsType(t, &sandbox.MemorySessionSandboxBindingStore{}, store)
+}
+
+func TestSelectSessionBindingStoreFallsBackToMemoryWhenNotRequired(t *testing.T) {
+ store, kind, err := selectSessionBindingStore(nil, false)
+ require.NoError(t, err)
+ require.Equal(t, "memory", kind)
+ require.IsType(t, &sandbox.MemorySessionSandboxBindingStore{}, store)
+}
+
+// fakeSessionLookup implements the narrow sessionExistenceLookup surface the
+// checker depends on. Keeping the surface narrow means the test double is a
+// couple of lines instead of the full 16-method SessionRepository stub.
+type fakeSessionLookup struct {
+ byID map[string]*types.Session
+ err error
+}
+
+func (f *fakeSessionLookup) GetByID(_ context.Context, tenantID uint64, id string) (*types.Session, error) {
+ if f.err != nil {
+ return nil, f.err
+ }
+ if s, ok := f.byID[id+"@"+strconv.FormatUint(tenantID, 10)]; ok {
+ return s, nil
+ }
+ return nil, gorm.ErrRecordNotFound
+}
+
+func TestSessionExistenceCheckerBackedByRepository(t *testing.T) {
+ repo := &fakeSessionLookup{
+ byID: map[string]*types.Session{
+ "session-a@42": {ID: "session-a", TenantID: 42},
+ },
+ }
+ checker := sessionExistenceCheckerFor(repo)
+
+ ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
+ require.NoError(t, err)
+ require.True(t, ok)
+
+ ok, err = checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "missing"})
+ require.NoError(t, err)
+ require.False(t, ok)
+}
+
+func TestSessionExistenceCheckerPropagatesTransientErrors(t *testing.T) {
+ fault := errors.New("database offline")
+ repo := &fakeSessionLookup{err: fault}
+ checker := sessionExistenceCheckerFor(repo)
+
+ ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
+ require.ErrorIs(t, err, fault)
+ require.False(t, ok)
+}
+
+func TestSessionExistenceCheckerFallsBackToPermissiveWhenLookupNil(t *testing.T) {
+ // Lite deployments (no database) still need to boot; a nil lookup
+ // hands us the permissive checker so the lifecycle coordinator never
+ // blocks resolution on a missing dependency.
+ checker := sessionExistenceCheckerFor(nil)
+ ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
+ require.NoError(t, err)
+ require.True(t, ok)
+}
diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go
index 7218388da..c205dc29a 100644
--- a/internal/handler/custom_agent.go
+++ b/internal/handler/custom_agent.go
@@ -17,6 +17,13 @@ import (
"github.com/gin-gonic/gin"
)
+// sandboxConfigLookup is the existence check an agent's sandbox selection needs.
+// Narrower than the full config service so this handler cannot grow a dependency
+// on config mutation.
+type sandboxConfigLookup interface {
+ Get(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
+}
+
// CustomAgentHandler defines the HTTP handler for custom agent operations
type CustomAgentHandler struct {
service interfaces.CustomAgentService
@@ -25,6 +32,9 @@ type CustomAgentHandler struct {
// userService 仅用于 list 接口批量回填 creator_name,作用见
// KnowledgeBaseHandler.userService。
userService interfaces.UserService
+ // sandboxConfigs validates an agent's sandbox backend selection. Optional —
+ // nil in partially-wired unit tests, where the selection is left unchecked.
+ sandboxConfigs sandboxConfigLookup
}
// NewCustomAgentHandler creates a new custom agent handler instance
@@ -33,12 +43,14 @@ func NewCustomAgentHandler(
imService *im.Service,
disabledRepo interfaces.TenantDisabledSharedAgentRepository,
userService interfaces.UserService,
+ sandboxConfigs *service.TenantSandboxConfigService,
) *CustomAgentHandler {
return &CustomAgentHandler{
- service: service,
- imService: imService,
- disabledRepo: disabledRepo,
- userService: userService,
+ service: service,
+ imService: imService,
+ disabledRepo: disabledRepo,
+ userService: userService,
+ sandboxConfigs: sandboxConfigs,
}
}
@@ -86,6 +98,10 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
c.Error(err)
return
}
+ if err := h.validateAgentSandboxConfig(ctx, req.Config); err != nil {
+ c.Error(err)
+ return
+ }
// Build agent object
agent := &types.CustomAgent{
@@ -329,6 +345,10 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
c.Error(err)
return
}
+ if err := h.validateAgentSandboxConfig(ctx, req.Config); err != nil {
+ c.Error(err)
+ return
+ }
// Build agent object
agent := &types.CustomAgent{
@@ -646,6 +666,34 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
})
}
+// validateAgentSandboxConfig rejects a selection the workspace does not have.
+//
+// Checking at save time is what makes the mistake fixable: a dangling reference
+// only fails when the agent next runs a skill, mid-conversation, as an opaque
+// resolution error with no hint about which agent to edit.
+func (h *CustomAgentHandler) validateAgentSandboxConfig(
+ ctx context.Context, cfg types.CustomAgentConfig,
+) error {
+ configID := strings.TrimSpace(cfg.SandboxConfigID)
+ if configID == "" || h.sandboxConfigs == nil {
+ // Empty means the deployment-wide default, which always exists.
+ return nil
+ }
+ tenantID, ok := types.TenantIDFromContext(ctx)
+ if !ok {
+ return errors.NewUnauthorizedError("Missing workspace context")
+ }
+ stored, err := h.sandboxConfigs.Get(ctx, tenantID, configID)
+ if err != nil {
+ return errors.NewInternalServerError("Failed to verify sandbox config").
+ WithDetails(err.Error())
+ }
+ if stored == nil {
+ return errors.NewBadRequestError("所选沙箱后端配置不存在,请重新选择")
+ }
+ return nil
+}
+
func authorizeAgentKnowledgeScope(ctx context.Context, cfg types.CustomAgentConfig) error {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok || !scope.IsKnowledgeBaseRestricted() {
diff --git a/internal/handler/custom_agent_sandbox_test.go b/internal/handler/custom_agent_sandbox_test.go
new file mode 100644
index 000000000..982fd02a6
--- /dev/null
+++ b/internal/handler/custom_agent_sandbox_test.go
@@ -0,0 +1,117 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ stderrors "errors"
+ "net/http"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// stubSandboxConfigLookup answers the existence check without a database.
+type stubSandboxConfigLookup struct {
+ entity *types.TenantSandboxConfigEntity
+ err error
+
+ lookups []string
+}
+
+func (s *stubSandboxConfigLookup) Get(
+ _ context.Context, _ uint64, id string,
+) (*types.TenantSandboxConfigEntity, error) {
+ s.lookups = append(s.lookups, id)
+ return s.entity, s.err
+}
+
+func agentTenantContext() context.Context {
+ return context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+}
+
+// The field must round-trip through the agent's JSON config column, since that
+// is where it is persisted (no dedicated column).
+func TestAgentConfigCarriesSandboxConfigID(t *testing.T) {
+ cfg := types.CustomAgentConfig{
+ AgentMode: "smart-reasoning",
+ SandboxConfigID: "cfg-a",
+ }
+
+ raw, err := json.Marshal(cfg)
+ require.NoError(t, err)
+ require.Contains(t, string(raw), `"sandbox_config_id":"cfg-a"`)
+
+ var back types.CustomAgentConfig
+ require.NoError(t, json.Unmarshal(raw, &back))
+ require.Equal(t, "cfg-a", back.SandboxConfigID)
+}
+
+// Empty must be omitted so existing agents keep an unchanged config payload.
+func TestAgentConfigOmitsEmptySandboxConfigID(t *testing.T) {
+ raw, err := json.Marshal(types.CustomAgentConfig{AgentMode: "quick-answer"})
+ require.NoError(t, err)
+ require.NotContains(t, string(raw), "sandbox_config_id")
+}
+
+// Saving a dangling reference must fail here with a readable message. Deferring
+// it means the agent looks fine until its first skill execution, which then dies
+// on an opaque resolver error mid-conversation.
+func TestAgentSandboxConfigValidationRejectsUnknownID(t *testing.T) {
+ lookup := &stubSandboxConfigLookup{}
+ h := &CustomAgentHandler{sandboxConfigs: lookup}
+
+ err := h.validateAgentSandboxConfig(agentTenantContext(),
+ types.CustomAgentConfig{SandboxConfigID: "cfg-gone"})
+
+ var appErr *apperrors.AppError
+ require.ErrorAs(t, err, &appErr)
+ require.Equal(t, http.StatusBadRequest, appErr.HTTPCode)
+ require.Equal(t, []string{"cfg-gone"}, lookup.lookups)
+}
+
+func TestAgentSandboxConfigValidationAcceptsExistingID(t *testing.T) {
+ lookup := &stubSandboxConfigLookup{
+ entity: &types.TenantSandboxConfigEntity{ID: "cfg-a", TenantID: 7},
+ }
+ h := &CustomAgentHandler{sandboxConfigs: lookup}
+
+ require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
+ types.CustomAgentConfig{SandboxConfigID: "cfg-a"}))
+}
+
+// Most agents run on the deployment default, so the common path must not pay for
+// a lookup - and must never be rejected for leaving the field blank.
+func TestAgentSandboxConfigValidationSkipsEmptyID(t *testing.T) {
+ lookup := &stubSandboxConfigLookup{}
+ h := &CustomAgentHandler{sandboxConfigs: lookup}
+
+ require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
+ types.CustomAgentConfig{SandboxConfigID: " "}))
+ require.Empty(t, lookup.lookups)
+}
+
+// A lookup failure is not the admin's fault; it must not read as "you picked a
+// config that does not exist".
+func TestAgentSandboxConfigValidationSurfacesLookupFailure(t *testing.T) {
+ lookup := &stubSandboxConfigLookup{err: stderrors.New("database is on fire")}
+ h := &CustomAgentHandler{sandboxConfigs: lookup}
+
+ err := h.validateAgentSandboxConfig(agentTenantContext(),
+ types.CustomAgentConfig{SandboxConfigID: "cfg-a"})
+
+ var appErr *apperrors.AppError
+ require.ErrorAs(t, err, &appErr)
+ require.Equal(t, http.StatusInternalServerError, appErr.HTTPCode)
+}
+
+// Partially-wired handlers appear in tests and in deployments without the
+// config service; they must not reject every agent that selects a backend.
+func TestAgentSandboxConfigValidationSkipsWhenServiceMissing(t *testing.T) {
+ h := &CustomAgentHandler{}
+
+ require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
+ types.CustomAgentConfig{SandboxConfigID: "cfg-a"}))
+}
diff --git a/internal/handler/sandbox_check.go b/internal/handler/sandbox_check.go
new file mode 100644
index 000000000..dc6cfefec
--- /dev/null
+++ b/internal/handler/sandbox_check.go
@@ -0,0 +1,324 @@
+package handler
+
+import (
+ "context"
+ stderrors "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// --- Sandbox connectivity check ---
+
+// SandboxCheckRequest is the body for POST /system/sandbox-check. Secrets may
+// arrive redacted; they are resolved against the workspace's stored config so
+// an admin can test without retyping an API key.
+type SandboxCheckRequest struct {
+ Config *types.TenantSandboxConfig `json:"config"`
+ // ConfigID lets an edit form test stored credentials while overriding only
+ // the fields the admin changed in the drawer.
+ ConfigID string `json:"config_id"`
+ // Deep additionally creates and destroys one sandbox, which is the only
+ // way to validate the template ID, Cube's proxy/envd data plane,
+ // in-sandbox execution, and outbound egress (CN + international probes,
+ // any one success). It consumes real sandbox time, so it is opt-in.
+ Deep bool `json:"deep"`
+}
+
+// SandboxCheckItem is one probe outcome. OK is nil when the probe was not
+// executed, which distinguishes "skipped" from "failed" in the UI.
+type SandboxCheckItem struct {
+ Name string `json:"name"`
+ OK *bool `json:"ok"`
+ Message string `json:"message,omitempty"`
+ LatencyMS int64 `json:"latency_ms,omitempty"`
+}
+
+// SandboxCheckResponse aggregates the probes for one sandbox configuration.
+type SandboxCheckResponse struct {
+ OK bool `json:"ok"`
+ Provider string `json:"provider"`
+ Checks []SandboxCheckItem `json:"checks"`
+ Capabilities map[string]bool `json:"capabilities,omitempty"`
+}
+
+// add records an executed probe. A single failure fails the whole result.
+func (r *SandboxCheckResponse) add(name string, ok bool, message string, latencyMS int64) {
+ value := ok
+ r.Checks = append(r.Checks, SandboxCheckItem{
+ Name: name, OK: &value, Message: message, LatencyMS: latencyMS,
+ })
+ if !ok {
+ r.OK = false
+ }
+}
+
+// skip records a probe that was not run; it never affects OK.
+func (r *SandboxCheckResponse) skip(name, message string) {
+ r.Checks = append(r.Checks, SandboxCheckItem{Name: name, OK: nil, Message: message})
+}
+
+// CheckSandboxConfig tests a sandbox configuration without persisting it.
+// @Summary 测试沙箱连通性
+// @Description 使用当前填写的参数测试沙箱后端连通性,不保存配置;deep=true 会额外创建并销毁一个沙箱
+// @Tags 系统
+// @Accept json
+// @Produce json
+// @Param body body SandboxCheckRequest true "沙箱配置"
+// @Success 200 {object} SandboxCheckResponse
+// @Router /system/sandbox-check [post]
+func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {
+ ctx := logger.CloneContext(c.Request.Context())
+
+ var req SandboxCheckRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "请求体格式错误"})
+ return
+ }
+ tenant, _ := types.TenantInfoFromContext(c.Request.Context())
+ if tenant == nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "空间为空"})
+ return
+ }
+
+ var stored *types.TenantSandboxConfig
+ incoming := req.Config
+ if req.ConfigID != "" {
+ if h.sandboxConfigSvc == nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "沙箱配置服务不可用"})
+ return
+ }
+ entity, err := h.sandboxConfigSvc.Get(ctx, tenant.ID, req.ConfigID)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})
+ return
+ }
+ if entity == nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "沙箱配置不存在"})
+ return
+ }
+ stored = entity.Config
+ if incoming == nil {
+ incoming = stored
+ }
+ }
+ merged, err := service.SanitizeSandboxConfig(incoming, stored)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})
+ return
+ }
+ effective, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DeploymentConfig())
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})
+ return
+ }
+
+ result := &SandboxCheckResponse{OK: true, Provider: string(effective.Type)}
+
+ client, err := sandbox.NewRemoteClientForCheck(effective)
+ if err != nil {
+ result.add("client_build", false, err.Error(), 0)
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
+ return
+ }
+
+ // Level 1: an authenticated control-plane call, which validates endpoint
+ // reachability AND credentials in a single round-trip.
+ start := time.Now()
+ healthErr := client.Health(ctx)
+ latency := time.Since(start).Milliseconds()
+ if healthErr != nil {
+ result.add("api_url_reachable", false, sandboxCheckReason(healthErr), latency)
+ result.skip("credential_valid", "未检测(控制面不可达)")
+ } else {
+ result.add("api_url_reachable", true, "", latency)
+ result.add("credential_valid", true, "", 0)
+ }
+
+ caps := client.Capabilities()
+ result.Capabilities = map[string]bool{
+ "supports_volumes": caps.SupportsVolumes,
+ "supports_pause_resume": caps.SupportsPauseResume,
+ "supports_reconnect": caps.SupportsReconnect,
+ }
+
+ if !req.Deep || healthErr != nil {
+ result.skip("template_exists", "未检测(需完整验证)")
+ result.skip("sandbox_exec", "未检测(需完整验证)")
+ result.skip("egress_available", "未检测(需完整验证)")
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
+ return
+ }
+
+ h.runDeepSandboxCheck(ctx, client, effective, result)
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
+}
+
+// runDeepSandboxCheck creates one throwaway sandbox and verifies a command can
+// run inside it. The sandbox is always deleted, including on failure.
+func (h *SystemHandler) runDeepSandboxCheck(
+ ctx context.Context,
+ client sandbox.RemoteSandboxClient,
+ cfg *sandbox.Config,
+ result *SandboxCheckResponse,
+) {
+ probeCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
+ defer cancel()
+
+ handle, err := client.Create(probeCtx, sandbox.RemoteCreateRequest{
+ TemplateID: sandbox.EffectiveTemplateID(cfg),
+ Timeout: sandbox.RemoteTimeoutPolicy{
+ Mode: sandbox.RemoteTimeoutExplicit,
+ Value: 2 * time.Minute,
+ Action: sandbox.RemoteOnTimeoutKill,
+ },
+ })
+ if err != nil {
+ result.add("template_exists", false, sandboxCheckReason(err), 0)
+ result.skip("sandbox_exec", "未检测(沙箱未创建)")
+ result.skip("egress_available", "未检测(沙箱未创建)")
+ return
+ }
+ defer func() {
+ // Detach from ctx so cleanup still runs if the request was cancelled;
+ // a leaked probe sandbox would otherwise sit there billing.
+ cleanupCtx, cleanupCancel := context.WithTimeout(
+ context.WithoutCancel(ctx), 30*time.Second)
+ defer cleanupCancel()
+ if err := client.Delete(cleanupCtx, handle.ID()); err != nil {
+ logger.Warnf(ctx, "[SandboxCheck] failed to delete probe sandbox %s: %v",
+ handle.ID(), err)
+ }
+ }()
+ result.add("template_exists", true, "", 0)
+
+ const marker = "weknora-ok"
+ start := time.Now()
+ execResult, err := client.Exec(probeCtx, handle, sandbox.RemoteExecRequest{
+ Command: "echo",
+ Args: []string{marker},
+ User: sandbox.DefaultSandboxExecUser,
+ Timeout: 30 * time.Second,
+ })
+ latency := time.Since(start).Milliseconds()
+ switch {
+ case err != nil:
+ result.add("sandbox_exec", false, sandboxCheckReason(err), latency)
+ result.skip("egress_available", "未检测(沙箱执行失败)")
+ return
+ case execResult == nil || !strings.Contains(execResult.Stdout, marker):
+ result.add("sandbox_exec", false, "命令输出与预期不符", latency)
+ result.skip("egress_available", "未检测(沙箱执行失败)")
+ return
+ default:
+ result.add("sandbox_exec", true, "", latency)
+ }
+
+ h.probeSandboxEgress(probeCtx, client, handle, result)
+}
+
+// egressProbeTargets are tried in order; the first reachable one passes
+// egress_available. Domestic and international endpoints cover regional
+// egress policies without requiring both to succeed.
+var egressProbeTargets = []struct {
+ label string
+ url string
+}{
+ {label: "cn:baidu", url: "https://www.baidu.com"},
+ {label: "intl:1.1.1.1", url: "https://1.1.1.1"},
+}
+
+// probeSandboxEgress verifies the sandbox can reach the public internet.
+// Any single target succeeding is enough — skill installs only need some
+// outbound path, not both CN and international reachability.
+func (h *SystemHandler) probeSandboxEgress(
+ ctx context.Context,
+ client sandbox.RemoteSandboxClient,
+ handle sandbox.RemoteSandboxHandle,
+ result *SandboxCheckResponse,
+) {
+ // Echo which target succeeded so the UI message is actionable when
+ // only one region is reachable. First success exits 0 immediately.
+ var b strings.Builder
+ for _, target := range egressProbeTargets {
+ fmt.Fprintf(&b,
+ `if curl -fsS -o /dev/null -m 8 -I %s; then echo %s; exit 0; fi; `,
+ shellSingleQuote(target.url), shellSingleQuote(target.label))
+ }
+ b.WriteString(`echo "all probes failed" >&2; exit 1`)
+
+ start := time.Now()
+ execResult, err := client.Exec(ctx, handle, sandbox.RemoteExecRequest{
+ Command: b.String(),
+ Shell: true,
+ User: sandbox.DefaultSandboxExecUser,
+ Timeout: 30 * time.Second,
+ })
+ latency := time.Since(start).Milliseconds()
+ switch {
+ case err != nil:
+ result.add("egress_available", false, sandboxCheckReason(err), latency)
+ case execResult == nil:
+ result.add("egress_available", false, "出网探测无返回", latency)
+ case execResult.Killed:
+ result.add("egress_available", false, "出网探测超时", latency)
+ case execResult.ExitCode != 0:
+ msg := strings.TrimSpace(execResult.Stderr)
+ if msg == "" {
+ msg = strings.TrimSpace(execResult.Stdout)
+ }
+ if msg == "" {
+ msg = "国内与国际探测目标均不可达"
+ }
+ result.add("egress_available", false, msg, latency)
+ default:
+ hit := strings.TrimSpace(execResult.Stdout)
+ if hit == "" {
+ hit = "ok"
+ }
+ result.add("egress_available", true, "reachable via "+hit, latency)
+ }
+}
+
+// shellSingleQuote wraps s for safe inclusion in a single-quoted shell string.
+func shellSingleQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+// 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 {
+ if err == nil {
+ return ""
+ }
+ var remoteErr *sandbox.RemoteError
+ if !stderrors.As(err, &remoteErr) {
+ return err.Error()
+ }
+ switch remoteErr.Kind {
+ case sandbox.RemoteErrorKindAuthentication:
+ return "认证失败:API Key 无效或无权限"
+ case sandbox.RemoteErrorKindNotFound:
+ return "资源不存在:请检查模板 ID"
+ case sandbox.RemoteErrorKindTimeout:
+ return "请求超时:端点不可达或响应过慢"
+ case sandbox.RemoteErrorKindUnavailable:
+ return "服务不可用:端点拒绝连接"
+ case sandbox.RemoteErrorKindCapacity:
+ return "配额不足或触发限流"
+ case sandbox.RemoteErrorKindUnsupported:
+ return "该后端不支持此操作"
+ case sandbox.RemoteErrorKindInvalidRequest:
+ return "参数无效:" + remoteErr.Message
+ default:
+ return remoteErr.Message
+ }
+}
diff --git a/internal/handler/sandbox_config.go b/internal/handler/sandbox_config.go
new file mode 100644
index 000000000..edfafa28c
--- /dev/null
+++ b/internal/handler/sandbox_config.go
@@ -0,0 +1,341 @@
+package handler
+
+import (
+ "context"
+ stderrors "errors"
+ "net/http"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+type sandboxConfigService interface {
+ Create(context.Context, uint64, service.CreateSandboxConfigInput) (*types.TenantSandboxConfigEntity, error)
+ List(context.Context, uint64) ([]*types.TenantSandboxConfigEntity, error)
+ Get(context.Context, uint64, string) (*types.TenantSandboxConfigEntity, error)
+ Update(context.Context, uint64, string, service.UpdateSandboxConfigInput) (*types.TenantSandboxConfigEntity, error)
+ Delete(context.Context, uint64, string, bool) error
+ Inventory(context.Context, uint64, string) (service.SandboxInventory, error)
+ WorkspaceScriptsDisabled(context.Context, uint64) (bool, error)
+ SetWorkspaceScriptsDisabled(context.Context, uint64, bool) error
+}
+
+type SandboxConfigHandler struct {
+ service sandboxConfigService
+ defaults *sandbox.ConfigDefaults
+}
+
+func NewSandboxConfigHandler(
+ service *service.TenantSandboxConfigService,
+ defaults *sandbox.ConfigDefaults,
+) *SandboxConfigHandler {
+ return &SandboxConfigHandler{service: service, defaults: defaults}
+}
+
+type sandboxConfigRequest struct {
+ Name string `json:"name" binding:"required"`
+ Description string `json:"description,omitempty"`
+ Config *types.TenantSandboxConfig `json:"config"`
+}
+
+// sandboxConfigResponse is the only outward projection of stored configs, so a
+// new read path cannot accidentally return decrypted credentials.
+type sandboxConfigResponse struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Description string `json:"description,omitempty"`
+ SandboxType string `json:"sandbox_type"`
+ Config *types.TenantSandboxConfig `json:"config"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+}
+
+func sandboxConfigTenantID(c *gin.Context) uint64 {
+ return c.GetUint64(types.TenantIDContextKey.String())
+}
+
+func toSandboxConfigResponse(e *types.TenantSandboxConfigEntity) sandboxConfigResponse {
+ if e == nil {
+ return sandboxConfigResponse{}
+ }
+ return sandboxConfigResponse{
+ ID: e.ID,
+ Name: e.Name,
+ Description: e.Description,
+ SandboxType: e.SandboxType,
+ Config: types.SandboxConfigForResponse(e.Config, true),
+ CreatedAt: e.CreatedAt,
+ UpdatedAt: e.UpdatedAt,
+ }
+}
+
+// respondSandboxesStillLive carries the exact inventory that refused the write;
+// recomputing it could race and show the admin a different reason.
+func respondSandboxesStillLive(c *gin.Context, inv service.SandboxInventory) {
+ c.JSON(http.StatusConflict, gin.H{
+ "success": false,
+ "error": gin.H{
+ "code": "sandboxes_still_live",
+ "message": "该配置仍有运行中或已暂停的沙箱,请先结束或删除相关会话,或新建一份配置",
+ "data": inv,
+ },
+ })
+}
+
+func respondSandboxInventoryUnverifiable(c *gin.Context) {
+ c.JSON(http.StatusConflict, gin.H{
+ "success": false,
+ "error": gin.H{
+ "code": "sandbox_inventory_unverifiable",
+ "message": "无法连接该后端核实是否仍有沙箱",
+ },
+ })
+}
+
+func respondSandboxConfigCordoned(c *gin.Context) {
+ c.JSON(http.StatusLocked, gin.H{
+ "success": false,
+ "error": gin.H{
+ "code": "sandbox_config_cordoned",
+ "message": "该配置正在被其他人修改,请稍后重试",
+ },
+ })
+}
+
+func respondSandboxConfigRefusal(c *gin.Context, err error) bool {
+ var liveErr *service.SandboxesStillLiveError
+ if stderrors.As(err, &liveErr) {
+ respondSandboxesStillLive(c, liveErr.Inventory)
+ return true
+ }
+ if stderrors.Is(err, service.ErrSandboxInventoryUnverifiable) {
+ respondSandboxInventoryUnverifiable(c)
+ return true
+ }
+ if stderrors.Is(err, repository.ErrSandboxConfigCordoned) {
+ respondSandboxConfigCordoned(c)
+ return true
+ }
+ return false
+}
+
+// respondSandboxConfigServiceError promotes the service's input-validation
+// sentinels to 400. They are matched as sentinels rather than by message so a
+// reworded error cannot silently start returning 500 for bad input.
+func respondSandboxConfigServiceError(c *gin.Context, err error) {
+ switch {
+ case stderrors.Is(err, service.ErrSandboxConfigNameRequired),
+ stderrors.Is(err, service.ErrNamedSandboxBackendUnsupported),
+ stderrors.Is(err, sandbox.ErrUnsupportedSandboxType),
+ stderrors.Is(err, sandbox.ErrUnsafeOutboundURL),
+ stderrors.Is(err, sandbox.ErrSandboxConfigIncomplete):
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ default:
+ c.Error(err)
+ }
+}
+
+// List godoc
+// @Summary List sandbox configs
+// @Description List workspace sandbox backend configs with credentials masked and deployment defaults included.
+// @Tags SandboxConfig
+// @Produce json
+// @Success 200 {object} map[string]interface{} "Sandbox configs and defaults"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs [get]
+func (h *SandboxConfigHandler) List(c *gin.Context) {
+ ctx := c.Request.Context()
+ tenantID := sandboxConfigTenantID(c)
+ configs, err := h.service.List(ctx, tenantID)
+ if err != nil {
+ c.Error(err)
+ return
+ }
+ disabled, err := h.service.WorkspaceScriptsDisabled(ctx, tenantID)
+ if err != nil {
+ c.Error(err)
+ return
+ }
+ data := make([]sandboxConfigResponse, 0, len(configs))
+ for _, cfg := range configs {
+ data = append(data, toSandboxConfigResponse(cfg))
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": data,
+ "defaults": h.defaults,
+ "workspace_scripts_disabled": disabled,
+ })
+}
+
+type workspacePolicyRequest struct {
+ ScriptsDisabled bool `json:"scripts_disabled"`
+}
+
+// SetWorkspacePolicy toggles script execution for agents that use the deployment default.
+func (h *SandboxConfigHandler) SetWorkspacePolicy(c *gin.Context) {
+ var req workspacePolicyRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ return
+ }
+ tenantID := sandboxConfigTenantID(c)
+ if err := h.service.SetWorkspaceScriptsDisabled(c.Request.Context(), tenantID, req.ScriptsDisabled); err != nil {
+ c.Error(err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "workspace_scripts_disabled": req.ScriptsDisabled})
+}
+
+// Create godoc
+// @Summary Create sandbox config
+// @Description Create a named workspace sandbox backend config. Credentials are masked in the response.
+// @Tags SandboxConfig
+// @Accept json
+// @Produce json
+// @Param request body sandboxConfigRequest true "Sandbox backend config"
+// @Success 201 {object} map[string]interface{} "Created sandbox config"
+// @Failure 400 {object} apperrors.AppError "Invalid request or validation failure"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs [post]
+func (h *SandboxConfigHandler) Create(c *gin.Context) {
+ var req sandboxConfigRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ return
+ }
+ created, err := h.service.Create(c.Request.Context(), sandboxConfigTenantID(c),
+ service.CreateSandboxConfigInput{
+ Name: req.Name,
+ Description: req.Description,
+ Config: req.Config,
+ })
+ if err != nil {
+ respondSandboxConfigServiceError(c, err)
+ return
+ }
+ c.JSON(http.StatusCreated, gin.H{"success": true, "data": toSandboxConfigResponse(created)})
+}
+
+// Get godoc
+// @Summary Get sandbox config
+// @Description Retrieve a workspace sandbox backend config with credentials masked.
+// @Tags SandboxConfig
+// @Produce json
+// @Param id path string true "Sandbox config ID"
+// @Success 200 {object} map[string]interface{} "Sandbox config"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Failure 404 {object} apperrors.AppError "Sandbox config not found"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs/{id} [get]
+func (h *SandboxConfigHandler) Get(c *gin.Context) {
+ cfg, err := h.service.Get(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"))
+ if err != nil {
+ c.Error(err)
+ return
+ }
+ if cfg == nil {
+ c.Error(apperrors.NewNotFoundError("sandbox config not found"))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": toSandboxConfigResponse(cfg)})
+}
+
+// Update godoc
+// @Summary Update sandbox config
+// @Description Update a sandbox backend config. Identity-field changes are refused while the config owns live or paused sandboxes.
+// @Tags SandboxConfig
+// @Accept json
+// @Produce json
+// @Param id path string true "Sandbox config ID"
+// @Param request body sandboxConfigRequest true "Updated sandbox config"
+// @Success 200 {object} map[string]interface{} "Updated sandbox config"
+// @Failure 400 {object} apperrors.AppError "Invalid request or validation failure"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Failure 404 {object} apperrors.AppError "Sandbox config not found"
+// @Failure 409 {object} map[string]interface{} "Live sandboxes or unverifiable inventory"
+// @Failure 423 {object} map[string]interface{} "Sandbox config is being modified by another request"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs/{id} [put]
+func (h *SandboxConfigHandler) Update(c *gin.Context) {
+ var req sandboxConfigRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ return
+ }
+ updated, err := h.service.Update(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"),
+ service.UpdateSandboxConfigInput{
+ Name: req.Name,
+ Description: req.Description,
+ Config: req.Config,
+ })
+ if err != nil {
+ if respondSandboxConfigRefusal(c, err) {
+ return
+ }
+ respondSandboxConfigServiceError(c, err)
+ return
+ }
+ if updated == nil {
+ c.Error(apperrors.NewNotFoundError("sandbox config not found"))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": toSandboxConfigResponse(updated)})
+}
+
+// Delete godoc
+// @Summary Delete sandbox config
+// @Description Soft-delete a sandbox backend config. force=true only overrides unverifiable provider inventory, never confirmed live sandboxes.
+// @Tags SandboxConfig
+// @Produce json
+// @Param id path string true "Sandbox config ID"
+// @Param force query bool false "Force delete when inventory is unverifiable"
+// @Success 200 {object} map[string]interface{} "Deletion success"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Failure 409 {object} map[string]interface{} "Live sandboxes or unverifiable inventory"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs/{id} [delete]
+func (h *SandboxConfigHandler) Delete(c *gin.Context) {
+ force := c.Query("force") == "true"
+ if err := h.service.Delete(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), force); err != nil {
+ if respondSandboxConfigRefusal(c, err) {
+ return
+ }
+ c.Error(err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// Inventory godoc
+// @Summary Inspect sandbox config inventory
+// @Description Return live/paused sandbox inventory and affected agent names for one config.
+// @Tags SandboxConfig
+// @Produce json
+// @Param id path string true "Sandbox config ID"
+// @Success 200 {object} map[string]interface{} "Sandbox inventory"
+// @Failure 401 {object} map[string]interface{} "Unauthorized"
+// @Security Bearer
+// @Security ApiKeyAuth
+// @Router /sandbox-configs/{id}/sandboxes [get]
+func (h *SandboxConfigHandler) Inventory(c *gin.Context) {
+ inv, err := h.service.Inventory(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"))
+ if err != nil {
+ c.Error(err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": inv})
+}
diff --git a/internal/handler/sandbox_config_test.go b/internal/handler/sandbox_config_test.go
new file mode 100644
index 000000000..01ddaf830
--- /dev/null
+++ b/internal/handler/sandbox_config_test.go
@@ -0,0 +1,249 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ stderrors "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/sandbox"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// Responses must never carry plaintext credentials, no matter which path
+// produced them.
+func TestSandboxConfigResponseMasksSecrets(t *testing.T) {
+ cfg := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIKey: "super-secret"},
+ EnvVars: map[string]string{"TOKEN": "also-secret"},
+ }
+ entity := &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ Name: "primary",
+ SandboxType: "e2b",
+ Config: cfg,
+ CreatedAt: time.Unix(1, 0),
+ UpdatedAt: time.Unix(2, 0),
+ }
+
+ body, err := json.Marshal(toSandboxConfigResponse(entity))
+ require.NoError(t, err)
+
+ require.NotContains(t, string(body), "super-secret")
+ require.NotContains(t, string(body), "also-secret")
+ require.Contains(t, string(body), types.RedactedSecretPlaceholder)
+}
+
+// The 409 must be machine-readable: the UI renders "release N sandboxes first"
+// from it rather than parsing a message string.
+func TestSandboxesStillLiveMapsTo409WithCounts(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.PUT("/sandbox-configs/:id", func(c *gin.Context) {
+ respondSandboxesStillLive(c, service.SandboxInventory{
+ SandboxCount: 3,
+ SessionIDs: []string{"s-1", "s-2"},
+ AgentNames: []string{"数据分析"},
+ })
+ })
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPut, "/sandbox-configs/cfg-a",
+ strings.NewReader(`{}`))
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusConflict, w.Code)
+
+ var payload struct {
+ Error struct {
+ Code string `json:"code"`
+ Data struct {
+ SandboxCount int `json:"sandbox_count"`
+ SessionIDs []string `json:"session_ids"`
+ AgentNames []string `json:"agent_names"`
+ } `json:"data"`
+ } `json:"error"`
+ }
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
+ require.Equal(t, "sandboxes_still_live", payload.Error.Code)
+ require.Equal(t, 3, payload.Error.Data.SandboxCount)
+ require.Len(t, payload.Error.Data.SessionIDs, 2)
+ require.Equal(t, []string{"数据分析"}, payload.Error.Data.AgentNames)
+}
+
+func TestSandboxInventoryUnverifiableMapsToDistinct409(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.DELETE("/sandbox-configs/:id", func(c *gin.Context) {
+ respondSandboxInventoryUnverifiable(c)
+ })
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-a", nil)
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusConflict, w.Code)
+
+ var payload struct {
+ Error struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ } `json:"error"`
+ }
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
+ require.Equal(t, "sandbox_inventory_unverifiable", payload.Error.Code)
+ require.Contains(t, payload.Error.Message, "无法连接")
+}
+
+func TestSandboxConfigDeletePassesForceQuery(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ svc := &fakeSandboxConfigService{}
+ h := &SandboxConfigHandler{service: svc, defaults: &sandbox.ConfigDefaults{}}
+ router := gin.New()
+ router.Use(func(c *gin.Context) {
+ c.Set(types.TenantIDContextKey.String(), uint64(42))
+ c.Next()
+ })
+ router.DELETE("/sandbox-configs/:id", h.Delete)
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-a?force=true", nil)
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, uint64(42), svc.deleteTenantID)
+ require.Equal(t, "cfg-a", svc.deleteID)
+ require.True(t, svc.deleteForce)
+
+ w = httptest.NewRecorder()
+ req = httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-b", nil)
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, "cfg-b", svc.deleteID)
+ require.False(t, svc.deleteForce)
+}
+
+// Bad input must not surface as a 500. The sentinels are matched with errors.Is
+// so rewording a message cannot silently reclassify these.
+func TestSandboxConfigValidationSentinelsMapTo400(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ for _, tc := range []struct {
+ name string
+ err error
+ }{
+ {"missing name", service.ErrSandboxConfigNameRequired},
+ {"named backend unsupported", service.ErrNamedSandboxBackendUnsupported},
+ {"unknown backend", fmt.Errorf("%w %q", sandbox.ErrUnsupportedSandboxType, "quantum")},
+ {"unsafe endpoint", fmt.Errorf("%w: host is private", sandbox.ErrUnsafeOutboundURL)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ respondSandboxConfigServiceError(c, tc.err)
+
+ require.Len(t, c.Errors, 1)
+ var appErr *apperrors.AppError
+ require.ErrorAs(t, c.Errors[0].Err, &appErr)
+ require.Equal(t, http.StatusBadRequest, appErr.HTTPCode)
+ })
+ }
+}
+
+// An unexpected failure must keep its original error so the middleware can map
+// it, rather than being flattened into a 400.
+func TestSandboxConfigUnexpectedErrorIsNotDowngraded(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ boom := stderrors.New("database is on fire")
+
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ respondSandboxConfigServiceError(c, boom)
+
+ require.Len(t, c.Errors, 1)
+ require.ErrorIs(t, c.Errors[0].Err, boom)
+}
+
+type fakeSandboxConfigService struct {
+ deleteTenantID uint64
+ deleteID string
+ deleteForce bool
+}
+
+func (s *fakeSandboxConfigService) Create(
+ context.Context,
+ uint64,
+ service.CreateSandboxConfigInput,
+) (*types.TenantSandboxConfigEntity, error) {
+ return nil, nil
+}
+
+func (s *fakeSandboxConfigService) List(
+ context.Context,
+ uint64,
+) ([]*types.TenantSandboxConfigEntity, error) {
+ return nil, nil
+}
+
+func (s *fakeSandboxConfigService) Get(
+ context.Context,
+ uint64,
+ string,
+) (*types.TenantSandboxConfigEntity, error) {
+ return nil, nil
+}
+
+func (s *fakeSandboxConfigService) Update(
+ context.Context,
+ uint64,
+ string,
+ service.UpdateSandboxConfigInput,
+) (*types.TenantSandboxConfigEntity, error) {
+ return nil, nil
+}
+
+func (s *fakeSandboxConfigService) Delete(
+ _ context.Context,
+ tenantID uint64,
+ id string,
+ force bool,
+) error {
+ s.deleteTenantID = tenantID
+ s.deleteID = id
+ s.deleteForce = force
+ return nil
+}
+
+func (s *fakeSandboxConfigService) Inventory(
+ context.Context,
+ uint64,
+ string,
+) (service.SandboxInventory, error) {
+ return service.SandboxInventory{}, nil
+}
+
+func (s *fakeSandboxConfigService) WorkspaceScriptsDisabled(
+ context.Context,
+ uint64,
+) (bool, error) {
+ return false, nil
+}
+
+func (s *fakeSandboxConfigService) SetWorkspaceScriptsDisabled(
+ context.Context,
+ uint64,
+ bool,
+) error {
+ return nil
+}
diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go
index f9088945b..25a403512 100644
--- a/internal/handler/session/agent_stream_handler.go
+++ b/internal/handler/session/agent_stream_handler.go
@@ -8,7 +8,9 @@ import (
"sync"
"time"
+ "github.com/Tencent/WeKnora/internal/agent/skills"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -21,6 +23,7 @@ import (
type AgentStreamHandler struct {
ctx context.Context
sessionID string
+ tenantID uint64 // Tenant that owns this session; used when persisting skill artifacts.
assistantMessageID string
requestID string
receivedAt time.Time // Handler entry timestamp, used for TTFB logging
@@ -30,6 +33,11 @@ type AgentStreamHandler struct {
eventBus *event.EventBus
+ // artifactCollector drains skill-generated files from the session
+ // sandbox after the agent completes. Nil when the sandbox backend
+ // doesn't support artifact collection or WeKnora was built without it.
+ artifactCollector *service.ArtifactCollector
+
// State tracking
knowledgeRefs []*types.SearchResult
finalAnswer string
@@ -76,20 +84,24 @@ func (h *AgentStreamHandler) composeFinalAnswer() string {
func NewAgentStreamHandler(
ctx context.Context,
sessionID, assistantMessageID, requestID string,
+ tenantID uint64,
receivedAt time.Time,
assistantMessage *types.Message,
streamManager interfaces.StreamManager,
eventBus *event.EventBus,
+ artifactCollector *service.ArtifactCollector,
) *AgentStreamHandler {
return &AgentStreamHandler{
ctx: ctx,
sessionID: sessionID,
+ tenantID: tenantID,
assistantMessageID: assistantMessageID,
requestID: requestID,
receivedAt: receivedAt,
assistantMessage: assistantMessage,
streamManager: streamManager,
eventBus: eventBus,
+ artifactCollector: artifactCollector,
knowledgeRefs: make([]*types.SearchResult, 0),
eventStartTimes: make(map[string]time.Time),
}
@@ -603,6 +615,34 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
h.assistantMessage.AgentSteps = agenttools.SanitizeAgentStepsForStorage(steps)
}
}
+
+ // Drain skill-generated files from the sandbox into persistent
+ // storage. Best-effort: any failure is logged and the turn is
+ // persisted without artifacts. Collect is a no-op when either the
+ // collector wasn't wired in, no sandbox is bound, or no files were
+ // produced — those cases must not disturb the completion path.
+ if h.artifactCollector != nil {
+ collectCtx := context.WithoutCancel(h.ctx)
+ artifacts, err := h.artifactCollector.Collect(
+ collectCtx,
+ h.sessionID,
+ h.assistantMessageID,
+ h.tenantID,
+ skills.ArtifactOutputDir(),
+ )
+ if err != nil {
+ logger.GetLogger(h.ctx).Warnf(
+ "artifact collect failed session=%s message=%s: %v",
+ h.sessionID, h.assistantMessageID, err,
+ )
+ } else if len(artifacts) > 0 {
+ h.assistantMessage.Artifacts = artifacts
+ logger.GetLogger(h.ctx).Infof(
+ "artifact collect attached %d file(s) to message=%s session=%s",
+ len(artifacts), h.assistantMessageID, h.sessionID,
+ )
+ }
+ }
}
// Fallback: if no answer events were streamed but we have a final answer,
@@ -646,19 +686,49 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
}
// Send completion event to stream manager so SSE can detect completion
+ completeData := map[string]interface{}{
+ "total_steps": data.TotalSteps,
+ "total_duration_ms": data.TotalDurationMs,
+ }
+ // Attach the freshly-collected artifacts so the frontend can render the
+ // download button without waiting for a page refresh. We strip the
+ // storage URL and any other server-only fields via publicArtifactViews
+ // — clients only ever download through /artifacts/:index which enforces
+ // tenant ownership.
+ if len(h.assistantMessage.Artifacts) > 0 {
+ completeData["artifacts"] = publicArtifactViews(h.assistantMessage.Artifacts)
+ }
if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeComplete,
Content: "",
Done: true,
Timestamp: time.Now(),
- Data: map[string]interface{}{
- "total_steps": data.TotalSteps,
- "total_duration_ms": data.TotalDurationMs,
- },
+ Data: completeData,
}); err != nil {
logger.GetLogger(h.ctx).Errorf("Append complete event to stream failed: %v", err)
}
return nil
}
+
+// publicArtifactViews returns a redacted view of the artifact list suitable
+// for direct serialization onto the SSE stream. The storage URL and any
+// other server-only fields are stripped; the frontend uses (index, name,
+// size, source_path, mod_time, created_at) to render the download drawer
+// and calls /artifacts/:index/download to fetch the bytes.
+func publicArtifactViews(list types.MessageArtifacts) []map[string]interface{} {
+ out := make([]map[string]interface{}, 0, len(list))
+ for i, a := range list {
+ out = append(out, map[string]interface{}{
+ "index": i,
+ "file_name": a.FileName,
+ "file_type": a.FileType,
+ "file_size": a.FileSize,
+ "source_path": a.SourcePath,
+ "mod_time": a.ModTime,
+ "created_at": a.CreatedAt,
+ })
+ }
+ return out
+}
diff --git a/internal/handler/session/artifact_download.go b/internal/handler/session/artifact_download.go
new file mode 100644
index 000000000..3abbf474d
--- /dev/null
+++ b/internal/handler/session/artifact_download.go
@@ -0,0 +1,310 @@
+package session
+
+import (
+ stderrors "errors"
+ "io"
+ "mime"
+ "net/http"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
+ "github.com/gin-gonic/gin"
+)
+
+// paramSessionID resolves the session-id URL parameter regardless of which
+// wildcard name the current route uses. GET-tree routes bind :id (to align
+// with /sessions/:id), while POST-tree routes typically bind :session_id.
+// Handlers call this helper instead of hard-coding one name so the same
+// function serves both trees.
+func paramSessionID(c *gin.Context) string {
+ if v := c.Param("session_id"); v != "" {
+ return v
+ }
+ return c.Param("id")
+}
+
+// ListSessionArtifacts godoc
+// @Summary 列出会话生成的产物文件
+// @Description 返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)
+// @Tags 会话
+// @Produce json
+// @Param session_id path string true "会话ID"
+// @Success 200 {object} map[string]interface{}
+// @Failure 404 {object} errors.AppError
+// @Security Bearer
+// @Router /sessions/{session_id}/artifacts [get]
+//
+// The endpoint powers the drawer that lists every file generated in the
+// session; it does NOT return the storage URL (only names/sizes/mtimes), so
+// clients cannot reach around the download endpoint by reading a
+// provider:// path from the API response.
+func (h *Handler) ListSessionArtifacts(c *gin.Context) {
+ ctx := c.Request.Context()
+ sessionID := secutils.SanitizeForLog(paramSessionID(c))
+ if sessionID == "" {
+ c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
+ return
+ }
+
+ // Ownership + tenant check: GetSession enforces both. Returning 404 for
+ // unknown / non-owned sessions matches the rest of the session routes.
+ if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
+ if stderrors.Is(err, errors.ErrSessionNotFound) {
+ c.Error(errors.NewNotFoundError(err.Error()))
+ return
+ }
+ c.Error(errors.NewInternalServerError(err.Error()))
+ return
+ }
+
+ artifacts, err := h.messageService.GetSessionArtifacts(ctx, sessionID)
+ if err != nil {
+ logger.Errorf(ctx, "list session artifacts failed: session=%s err=%v", sessionID, err)
+ c.Error(errors.NewInternalServerError(err.Error()))
+ return
+ }
+
+ // Strip the storage URL before serialising to the client; the URL is a
+ // server-side implementation detail (provider:// path) that must never
+ // escape the process. The client references artifacts by index in the
+ // download URL instead.
+ items := make([]artifactListItem, 0, len(artifacts))
+ for i, a := range artifacts {
+ items = append(items, artifactListItem{
+ Index: i,
+ FileName: a.FileName,
+ FileType: a.FileType,
+ FileSize: a.FileSize,
+ SourcePath: a.SourcePath,
+ ModTime: a.ModTime,
+ CreatedAt: a.CreatedAt,
+ })
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": items,
+ })
+}
+
+// ListMessageArtifacts returns just the artifacts attached to a single
+// assistant message. Used by the "download files from this reply" button on
+// each bot message.
+//
+// Same-tenant/same-owner check flows through h.sessionService.GetSession
+// exactly like ListSessionArtifacts.
+//
+// @Router /sessions/{session_id}/messages/{message_id}/artifacts [get]
+func (h *Handler) ListMessageArtifacts(c *gin.Context) {
+ ctx := c.Request.Context()
+ sessionID := secutils.SanitizeForLog(paramSessionID(c))
+ messageID := secutils.SanitizeForLog(c.Param("message_id"))
+ if sessionID == "" || messageID == "" {
+ c.Error(errors.NewBadRequestError("session_id and message_id are required"))
+ return
+ }
+
+ if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
+ if stderrors.Is(err, errors.ErrSessionNotFound) {
+ c.Error(errors.NewNotFoundError(err.Error()))
+ return
+ }
+ c.Error(errors.NewInternalServerError(err.Error()))
+ return
+ }
+
+ msg, err := h.messageService.GetMessage(ctx, sessionID, messageID)
+ if err != nil || msg == nil {
+ c.Error(errors.NewNotFoundError("message not found"))
+ return
+ }
+
+ items := make([]artifactListItem, 0, len(msg.Artifacts))
+ for i, a := range msg.Artifacts {
+ items = append(items, artifactListItem{
+ Index: i,
+ FileName: a.FileName,
+ FileType: a.FileType,
+ FileSize: a.FileSize,
+ SourcePath: a.SourcePath,
+ ModTime: a.ModTime,
+ CreatedAt: a.CreatedAt,
+ })
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": items,
+ })
+}
+
+// DownloadMessageArtifact streams a single skill-generated file to the
+// client. Clients reference the artifact by its position (:index) in the
+// assistant message's Artifacts array; the storage URL never leaves the
+// server so callers cannot pivot to arbitrary blobs.
+//
+// @Router /sessions/{session_id}/messages/{message_id}/artifacts/{index}/download [get]
+func (h *Handler) DownloadMessageArtifact(c *gin.Context) {
+ ctx := c.Request.Context()
+
+ sessionID := secutils.SanitizeForLog(paramSessionID(c))
+ messageID := secutils.SanitizeForLog(c.Param("message_id"))
+ indexParam := c.Param("index")
+ if sessionID == "" || messageID == "" || indexParam == "" {
+ c.Error(errors.NewBadRequestError("session_id, message_id and index are required"))
+ return
+ }
+ index, err := strconv.Atoi(indexParam)
+ if err != nil || index < 0 {
+ c.Error(errors.NewBadRequestError("invalid artifact index"))
+ return
+ }
+
+ // Ownership check: GetSession returns ErrSessionNotFound when the
+ // session doesn't belong to the calling tenant/user, so a 404 covers
+ // both "not found" and "forbidden" without leaking existence.
+ if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
+ if stderrors.Is(err, errors.ErrSessionNotFound) {
+ c.Error(errors.NewNotFoundError(err.Error()))
+ return
+ }
+ c.Error(errors.NewInternalServerError(err.Error()))
+ return
+ }
+
+ msg, err := h.messageService.GetMessage(ctx, sessionID, messageID)
+ if err != nil || msg == nil {
+ c.Error(errors.NewNotFoundError("message not found"))
+ return
+ }
+ if index >= len(msg.Artifacts) {
+ c.Error(errors.NewNotFoundError("artifact index out of range"))
+ return
+ }
+ artifact := msg.Artifacts[index]
+ if artifact.URL == "" {
+ c.Error(errors.NewNotFoundError("artifact storage path missing"))
+ return
+ }
+
+ if h.fileService == nil {
+ c.Error(errors.NewInternalServerError("file service unavailable"))
+ return
+ }
+ reader, err := h.fileService.GetFile(ctx, artifact.URL)
+ if err != nil {
+ logger.Warnf(ctx, "artifact download read failed: session=%s message=%s idx=%d err=%v",
+ sessionID, messageID, index, err)
+ c.Error(errors.NewNotFoundError("artifact blob missing"))
+ return
+ }
+ defer reader.Close()
+
+ // Force download semantics — artifacts are never rendered inline, matching
+ // the /files endpoint's active-content protection.
+ c.Header("Content-Type", mimeTypeFor(artifact.FileName))
+ c.Header("X-Content-Type-Options", "nosniff")
+ c.Header("Content-Disposition", buildAttachmentHeader(artifact.FileName))
+ if artifact.FileSize > 0 {
+ c.Header("Content-Length", strconv.FormatInt(artifact.FileSize, 10))
+ }
+ c.Status(http.StatusOK)
+ if _, err := io.Copy(c.Writer, reader); err != nil {
+ logger.Warnf(ctx, "artifact download stream failed: session=%s message=%s idx=%d err=%v",
+ sessionID, messageID, index, err)
+ }
+}
+
+// artifactListItem is the JSON shape returned by ListSessionArtifacts /
+// ListMessageArtifacts. It intentionally omits the URL: clients reference
+// each artifact through its position in the parent message's Artifacts
+// array so the storage path never leaves the server.
+type artifactListItem struct {
+ Index int `json:"index"`
+ FileName string `json:"file_name"`
+ FileType string `json:"file_type"`
+ FileSize int64 `json:"file_size"`
+ SourcePath string `json:"source_path"`
+ // time-typed fields serialise as RFC3339 strings — same convention as
+ // the rest of the messages API.
+ ModTime any `json:"mod_time"`
+ CreatedAt any `json:"created_at"`
+}
+
+// mimeTypeFor picks a Content-Type by extension and falls back to
+// application/octet-stream so unknown types force a download prompt rather
+// than being sniffed. Kept private to this file — the /files route has a
+// stricter version with an SVG-neutralising branch; we don't need that here
+// because Content-Disposition already blocks inline rendering.
+func mimeTypeFor(name string) string {
+ ext := strings.ToLower(filepath.Ext(name))
+ if ext == "" {
+ return "application/octet-stream"
+ }
+ if ct := mime.TypeByExtension(ext); ct != "" {
+ return ct
+ }
+ return "application/octet-stream"
+}
+
+// buildAttachmentHeader returns a Content-Disposition value that preserves
+// non-ASCII filenames (RFC 5987) while providing a safe fallback for
+// ASCII-only clients.
+func buildAttachmentHeader(name string) string {
+ // Strip control characters + quotes; keep the human-readable name.
+ ascii := strings.Map(func(r rune) rune {
+ if r < 0x20 || r == 0x7f {
+ return -1
+ }
+ if r == '"' || r == '\\' {
+ return '_'
+ }
+ if r > 0x7e {
+ return -1
+ }
+ return r
+ }, name)
+ if ascii == "" {
+ ascii = "download"
+ }
+ encoded := (&urlPathEscaper{}).escape(name)
+ return "attachment; filename=\"" + ascii + "\"; filename*=UTF-8''" + encoded
+}
+
+// urlPathEscaper is a minimal RFC 3986 percent-encoder for the subset of
+// bytes allowed in a filename*= value. We inline it to avoid importing
+// net/url just for a two-line call, and because url.PathEscape encodes
+// spaces as "+" (form-encoding) which HTTP clients then decode as literal
+// "+" characters in the filename.
+type urlPathEscaper struct{}
+
+// escape percent-encodes every byte outside the "attr-char" grammar of RFC 5987.
+// See https://datatracker.ietf.org/doc/html/rfc5987#section-3.2.1
+func (urlPathEscaper) escape(s string) string {
+ var b strings.Builder
+ b.Grow(len(s))
+ const hex = "0123456789ABCDEF"
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ switch {
+ case (c >= 'A' && c <= 'Z'), (c >= 'a' && c <= 'z'), (c >= '0' && c <= '9'):
+ b.WriteByte(c)
+ case c == '-' || c == '.' || c == '_' || c == '~':
+ b.WriteByte(c)
+ default:
+ b.WriteByte('%')
+ b.WriteByte(hex[c>>4])
+ b.WriteByte(hex[c&0x0f])
+ }
+ }
+ return b.String()
+}
+
+// ensureAssistantOwnsArtifact is a small helper reserved for future
+// authorisation refinements (per-message role checks). It is unused today
+// but kept close to the handlers so future changes stay obvious.
+var _ = types.MessageArtifact{}
diff --git a/internal/handler/session/artifact_download_test.go b/internal/handler/session/artifact_download_test.go
new file mode 100644
index 000000000..e58a1d202
--- /dev/null
+++ b/internal/handler/session/artifact_download_test.go
@@ -0,0 +1,271 @@
+package session
+
+import (
+ "context"
+ stderrors "errors"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+// -----------------------------------------------------------------------------
+// Test doubles
+//
+// The download handler only touches three collaborators: SessionService (for
+// ownership check), MessageService (for the message + artifact list), and
+// FileService (for the blob stream). We embed the full interfaces so the
+// zero-value struct compiles, then override just the methods each test
+// exercises. A stray call to an un-stubbed method deliberately nil-panics
+// so the failure surfaces immediately.
+// -----------------------------------------------------------------------------
+
+type stubSessionServiceForArtifacts struct {
+ interfaces.SessionService
+ getSession func(ctx context.Context, id string) (*types.Session, error)
+}
+
+func (s *stubSessionServiceForArtifacts) GetSession(ctx context.Context, id string) (*types.Session, error) {
+ return s.getSession(ctx, id)
+}
+
+type stubMessageServiceForArtifacts struct {
+ interfaces.MessageService
+ getMessage func(ctx context.Context, sessionID, id string) (*types.Message, error)
+ getSessionArtifact func(ctx context.Context, sessionID string) (types.MessageArtifacts, error)
+}
+
+func (s *stubMessageServiceForArtifacts) GetMessage(ctx context.Context, sessionID, id string) (*types.Message, error) {
+ return s.getMessage(ctx, sessionID, id)
+}
+
+func (s *stubMessageServiceForArtifacts) GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error) {
+ if s.getSessionArtifact == nil {
+ return types.MessageArtifacts{}, nil
+ }
+ return s.getSessionArtifact(ctx, sessionID)
+}
+
+// fakeArtifactFileService serves canned bytes for a single URL.
+type fakeArtifactFileService struct {
+ interfaces.FileService
+ url string
+ data []byte
+}
+
+func (f *fakeArtifactFileService) GetFile(_ context.Context, url string) (io.ReadCloser, error) {
+ if url != f.url {
+ return nil, stderrors.New("not found")
+ }
+ return io.NopCloser(strings.NewReader(string(f.data))), nil
+}
+
+func (f *fakeArtifactFileService) SaveFile(_ context.Context, _ *multipart.FileHeader, _ uint64, _ string) (string, error) {
+ return "", nil
+}
+
+func (f *fakeArtifactFileService) SaveBytes(_ context.Context, _ []byte, _ uint64, _ string, _ bool) (string, error) {
+ return "", nil
+}
+
+func (f *fakeArtifactFileService) GetFileURL(_ context.Context, _ string) (string, error) {
+ return "", nil
+}
+
+func (f *fakeArtifactFileService) DeleteFile(_ context.Context, _ string) error {
+ return nil
+}
+
+// -----------------------------------------------------------------------------
+// Router builder
+// -----------------------------------------------------------------------------
+
+func newArtifactTestRouter(h *Handler) *gin.Engine {
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ r.Use(middleware.ErrorHandler())
+ // Match the production route's wildcard names (see router.go — GET tree
+ // binds :id to align with /sessions/:id) so paramSessionID resolves via
+ // the same code path exercised in prod.
+ r.GET("/sessions/:id/artifacts", h.ListSessionArtifacts)
+ r.GET("/sessions/:id/messages/:message_id/artifacts", h.ListMessageArtifacts)
+ r.GET("/sessions/:id/messages/:message_id/artifacts/:index/download", h.DownloadMessageArtifact)
+ return r
+}
+
+// -----------------------------------------------------------------------------
+// Tests
+// -----------------------------------------------------------------------------
+
+func TestDownloadMessageArtifact_HappyPath(t *testing.T) {
+ sessionID := "sess-1"
+ messageID := "msg-1"
+ url := "fake://tenant-42/report.pptx"
+ body := []byte("PPTX-BYTES")
+
+ h := &Handler{
+ sessionService: &stubSessionServiceForArtifacts{
+ getSession: func(_ context.Context, id string) (*types.Session, error) {
+ if id != sessionID {
+ return nil, apperrors.ErrSessionNotFound
+ }
+ return &types.Session{ID: id, TenantID: 42}, nil
+ },
+ },
+ messageService: &stubMessageServiceForArtifacts{
+ getMessage: func(_ context.Context, sid, mid string) (*types.Message, error) {
+ if sid != sessionID || mid != messageID {
+ return nil, nil
+ }
+ return &types.Message{
+ ID: mid, SessionID: sid,
+ Artifacts: types.MessageArtifacts{{
+ URL: url,
+ FileName: "报告.pptx", // non-ASCII to exercise RFC 5987 encoding
+ FileType: ".pptx",
+ FileSize: int64(len(body)),
+ }},
+ }, nil
+ },
+ },
+ fileService: &fakeArtifactFileService{url: url, data: body},
+ }
+
+ router := newArtifactTestRouter(h)
+ req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/0/download", nil)
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
+ }
+ if got := w.Body.String(); got != string(body) {
+ t.Fatalf("body = %q, want %q", got, string(body))
+ }
+ cd := w.Header().Get("Content-Disposition")
+ if !strings.HasPrefix(cd, "attachment;") {
+ t.Fatalf("Content-Disposition = %q, want attachment prefix", cd)
+ }
+ if !strings.Contains(cd, "filename*=UTF-8''") {
+ t.Fatalf("Content-Disposition = %q, want RFC 5987 filename*", cd)
+ }
+ if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {
+ t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
+ }
+}
+
+func TestDownloadMessageArtifact_SessionNotOwnedReturns404(t *testing.T) {
+ h := &Handler{
+ sessionService: &stubSessionServiceForArtifacts{
+ getSession: func(_ context.Context, _ string) (*types.Session, error) {
+ return nil, apperrors.ErrSessionNotFound
+ },
+ },
+ }
+ router := newArtifactTestRouter(h)
+ req := httptest.NewRequest(http.MethodGet, "/sessions/sess-x/messages/msg-x/artifacts/0/download", nil)
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+}
+
+func TestDownloadMessageArtifact_IndexOutOfRange(t *testing.T) {
+ sessionID := "sess-1"
+ messageID := "msg-1"
+ h := &Handler{
+ sessionService: &stubSessionServiceForArtifacts{
+ getSession: func(_ context.Context, _ string) (*types.Session, error) {
+ return &types.Session{ID: sessionID, TenantID: 42}, nil
+ },
+ },
+ messageService: &stubMessageServiceForArtifacts{
+ getMessage: func(_ context.Context, _, _ string) (*types.Message, error) {
+ return &types.Message{ID: messageID, SessionID: sessionID, Artifacts: types.MessageArtifacts{}}, nil
+ },
+ },
+ }
+ router := newArtifactTestRouter(h)
+ req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/7/download", nil)
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404 for out-of-range index", w.Code)
+ }
+}
+
+func TestDownloadMessageArtifact_InvalidIndex(t *testing.T) {
+ h := &Handler{
+ sessionService: &stubSessionServiceForArtifacts{
+ getSession: func(_ context.Context, _ string) (*types.Session, error) {
+ return &types.Session{ID: "sess-1", TenantID: 42}, nil
+ },
+ },
+ }
+ router := newArtifactTestRouter(h)
+ req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/not-a-number/download", nil)
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 for non-integer index", w.Code)
+ }
+}
+
+func TestListSessionArtifacts_StripsURL(t *testing.T) {
+ h := &Handler{
+ sessionService: &stubSessionServiceForArtifacts{
+ getSession: func(_ context.Context, _ string) (*types.Session, error) {
+ return &types.Session{ID: "sess-1", TenantID: 42}, nil
+ },
+ },
+ messageService: &stubMessageServiceForArtifacts{
+ getSessionArtifact: func(_ context.Context, _ string) (types.MessageArtifacts, error) {
+ return types.MessageArtifacts{
+ {URL: "fake://internal/1", FileName: "a.txt", FileSize: 1, CreatedAt: time.Now()},
+ }, nil
+ },
+ },
+ }
+ router := newArtifactTestRouter(h)
+ req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/artifacts", nil)
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
+ }
+ // The URL must not appear in the response body: it's an internal
+ // storage path and leaking it defeats the download endpoint's
+ // ownership check.
+ if strings.Contains(w.Body.String(), "fake://internal/1") {
+ t.Fatalf("response body leaked storage URL: %s", w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "a.txt") {
+ t.Fatalf("response body missing file name: %s", w.Body.String())
+ }
+}
+
+func TestBuildAttachmentHeader_CJK(t *testing.T) {
+ // The RFC 5987 filename* segment must percent-encode every non-attr-char
+ // byte so downstream browsers preserve "报告.pptx" instead of mojibake.
+ got := buildAttachmentHeader("报告.pptx")
+ if !strings.Contains(got, "filename=") {
+ t.Fatalf("missing ASCII filename fallback: %q", got)
+ }
+ if !strings.Contains(got, "filename*=UTF-8''") {
+ t.Fatalf("missing RFC 5987 filename*: %q", got)
+ }
+ // Non-ASCII bytes must be percent-encoded (never appear literally).
+ if strings.ContainsRune(got, '报') {
+ t.Fatalf("filename* contains raw CJK: %q", got)
+ }
+}
diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go
index 37174998b..c87a74926 100644
--- a/internal/handler/session/handler.go
+++ b/internal/handler/session/handler.go
@@ -4,6 +4,7 @@ import (
stderrors "errors"
"net/http"
+ "github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
@@ -31,6 +32,10 @@ type Handler struct {
modelService interfaces.ModelService // Service for model management (VLM access)
attachmentProcessor *AttachmentProcessor // Processor for file attachments
temporaryDocuments interfaces.TemporaryDocumentService
+ // artifactCollector drains skill-generated files from the session sandbox
+ // after an agent turn completes. May be nil when the sandbox backend does
+ // not support artifact collection; handlers must check before using.
+ artifactCollector *service.ArtifactCollector
}
// NewHandler creates a new instance of Handler with all necessary dependencies
@@ -51,6 +56,7 @@ func NewHandler(
documentReader interfaces.DocumentReader,
imageResolver *docparser.ImageResolver,
temporaryDocuments interfaces.TemporaryDocumentService,
+ artifactCollector *service.ArtifactCollector,
) *Handler {
return &Handler{
sessionService: sessionService,
@@ -67,6 +73,7 @@ func NewHandler(
storageResolver: storageResolver,
modelService: modelService,
temporaryDocuments: temporaryDocuments,
+ artifactCollector: artifactCollector,
attachmentProcessor: NewAttachmentProcessor(
fileService,
documentReader,
diff --git a/internal/handler/session/helpers.go b/internal/handler/session/helpers.go
index 0d2b89b0e..b1e9ce5c1 100644
--- a/internal/handler/session/helpers.go
+++ b/internal/handler/session/helpers.go
@@ -285,13 +285,14 @@ func (h *Handler) createAssistantMessage(ctx context.Context, assistantMessage *
func (h *Handler) setupStreamHandler(
ctx context.Context,
sessionID, assistantMessageID, requestID string,
+ tenantID uint64,
receivedAt time.Time,
assistantMessage *types.Message,
eventBus *event.EventBus,
) *AgentStreamHandler {
streamHandler := NewAgentStreamHandler(
- ctx, sessionID, assistantMessageID, requestID, receivedAt,
- assistantMessage, h.streamManager, eventBus,
+ ctx, sessionID, assistantMessageID, requestID, tenantID, receivedAt,
+ assistantMessage, h.streamManager, eventBus, h.artifactCollector,
)
streamHandler.Subscribe()
return streamHandler
diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go
index a448555cb..46cdfb1d3 100644
--- a/internal/handler/session/qa.go
+++ b/internal/handler/session/qa.go
@@ -24,6 +24,11 @@ import (
"github.com/google/uuid"
)
+const (
+ maxAttachmentUploadsPerRequest = 5
+ maxAttachmentUploadTotalBytes = int64(100 * 1024 * 1024)
+)
+
// qaRequestContext holds all the common data needed for QA requests
type qaRequestContext struct {
ctx context.Context
@@ -213,15 +218,17 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
if len(request.AttachmentUploads) > 0 {
logger.Infof(ctx, "[%s] processing %d attachment(s)", logPrefix, len(request.AttachmentUploads))
- // MAX_FILE_SIZE_MB env (50MB default). See utils/filesize.go for
- // why this is deploy-time-only rather than a runtime setting.
- maxSizeMB := secutils.GetMaxFileSizeMB()
- maxSize := maxSizeMB * 1024 * 1024
- for i, upload := range request.AttachmentUploads {
- if upload.FileSize > maxSize {
- return nil, nil, errors.NewBadRequestError(
- fmt.Sprintf("attachment %d exceeds size limit of %dMB", i+1, maxSizeMB))
- }
+ // Decode first and validate actual bytes. Client-declared file_size is
+ // metadata only and must not be trusted for memory or sandbox limits.
+ maxSize := secutils.GetMaxFileSize()
+ decodedAttachments, decodeErr := decodeAndValidateAttachmentUploads(
+ request.AttachmentUploads,
+ maxAttachmentUploadsPerRequest,
+ maxSize,
+ maxAttachmentUploadTotalBytes,
+ )
+ if decodeErr != nil {
+ return nil, nil, errors.NewBadRequestError(decodeErr.Error())
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
@@ -257,14 +264,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
go func(idx int, att AttachmentUpload) {
defer wg.Done()
- data, err := DecodeBase64Attachment(att.Data)
- if err != nil {
- errChan <- fmt.Errorf("attachment %d decode failed: %w", idx+1, err)
- return
- }
-
processed, err := h.attachmentProcessor.ProcessAttachment(
- attachmentRuntimeCtx, data, att.FileName, att.FileSize, tenantID, asrModelID,
+ attachmentRuntimeCtx, decodedAttachments[idx], att.FileName, int64(len(decodedAttachments[idx])), tenantID, asrModelID,
)
if err != nil {
errChan <- fmt.Errorf("attachment %d processing failed: %w", idx+1, err)
@@ -391,6 +392,34 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
return reqCtx, &request, nil
}
+func decodeAndValidateAttachmentUploads(
+ uploads []AttachmentUpload,
+ maxCount int,
+ maxFileBytes, maxTotalBytes int64,
+) ([][]byte, error) {
+ if len(uploads) > maxCount {
+ return nil, fmt.Errorf("at most %d attachments are allowed per request", maxCount)
+ }
+ decoded := make([][]byte, len(uploads))
+ var total int64
+ for i, upload := range uploads {
+ data, err := DecodeBase64Attachment(upload.Data)
+ if err != nil {
+ return nil, fmt.Errorf("attachment %d decode failed: %w", i+1, err)
+ }
+ actualSize := int64(len(data))
+ if actualSize > maxFileBytes {
+ return nil, fmt.Errorf("attachment %d exceeds size limit of %d bytes", i+1, maxFileBytes)
+ }
+ total += actualSize
+ if total > maxTotalBytes {
+ return nil, fmt.Errorf("attachments exceed total request limit of %d bytes", maxTotalBytes)
+ }
+ decoded[i] = data
+ }
+ return decoded, nil
+}
+
func buildMessageExecutionContext(
ctx context.Context,
agent *types.CustomAgent,
@@ -597,6 +626,10 @@ func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool) *
logger.Infof(reqCtx.ctx, "Using effective tenant %d for shared agent (model/KB/MCP)", reqCtx.effectiveTenantID)
}
}
+ // The session's sandbox stays bound to the session owner even when the
+ // borrowed tenant above drives everything else, because DeleteSession tears
+ // that sandbox down from a request that only knows the session's tenant.
+ baseCtx = types.WithSandboxTenantID(baseCtx, reqCtx.session.TenantID)
// Create EventBus and cancellable context
eventBus := event.NewEventBus()
@@ -625,7 +658,7 @@ func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool) *
// Setup stream handler
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
- reqCtx.requestID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus)
+ reqCtx.requestID, reqCtx.session.TenantID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus)
// Generate title if needed
if generateTitle && reqCtx.session.Title == "" {
diff --git a/internal/handler/session/qa_attachment_test.go b/internal/handler/session/qa_attachment_test.go
new file mode 100644
index 000000000..9e4056bc2
--- /dev/null
+++ b/internal/handler/session/qa_attachment_test.go
@@ -0,0 +1,62 @@
+package session
+
+import (
+ "encoding/base64"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func encodedAttachment(data string, declaredSize int64) AttachmentUpload {
+ return AttachmentUpload{
+ Data: base64.StdEncoding.EncodeToString([]byte(data)),
+ FileName: "file.txt",
+ FileSize: declaredSize,
+ }
+}
+
+func TestDecodeAndValidateAttachmentUploadsUsesActualBytes(t *testing.T) {
+ uploads := []AttachmentUpload{encodedAttachment("123456", 1)}
+
+ _, err := decodeAndValidateAttachmentUploads(uploads, 5, 5, 100)
+
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "exceeds size limit")
+}
+
+func TestDecodeAndValidateAttachmentUploadsBoundsCountAndTotal(t *testing.T) {
+ t.Run("count", func(t *testing.T) {
+ uploads := make([]AttachmentUpload, 6)
+ for i := range uploads {
+ uploads[i] = encodedAttachment("x", 1)
+ }
+ _, err := decodeAndValidateAttachmentUploads(uploads, 5, 10, 100)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "at most 5")
+ })
+
+ t.Run("total", func(t *testing.T) {
+ uploads := []AttachmentUpload{
+ encodedAttachment(strings.Repeat("a", 6), 6),
+ encodedAttachment(strings.Repeat("b", 6), 6),
+ }
+ _, err := decodeAndValidateAttachmentUploads(uploads, 5, 10, 10)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "total request limit")
+ })
+}
+
+func TestDecodeAndValidateAttachmentUploadsReturnsDecodedBytes(t *testing.T) {
+ decoded, err := decodeAndValidateAttachmentUploads(
+ []AttachmentUpload{encodedAttachment("hello", 999)},
+ 5,
+ 10,
+ 10,
+ )
+
+ require.NoError(t, err)
+ require.Len(t, decoded, 1)
+ assert.Equal(t, []byte("hello"), decoded[0])
+}
diff --git a/internal/handler/system.go b/internal/handler/system.go
index 69ff853dd..d9a810d5f 100644
--- a/internal/handler/system.go
+++ b/internal/handler/system.go
@@ -62,6 +62,7 @@ type SystemHandler struct {
// singleton tenant.StorageEngineConfig. Optional — nil in partially-wired
// unit tests, in which case only the legacy config is consulted.
storageBackendRepo interfaces.StorageBackendRepository
+ sandboxConfigSvc sandboxConfigService
}
// NewSystemHandler creates a new system handler
@@ -76,6 +77,7 @@ func NewSystemHandler(cfg *config.Config,
taskInspector interfaces.TaskInspector,
knowledgeSvc interfaces.KnowledgeService,
storageBackendRepo interfaces.StorageBackendRepository,
+ sandboxConfigSvc *service.TenantSandboxConfigService,
) *SystemHandler {
return &SystemHandler{
cfg: cfg,
@@ -89,6 +91,7 @@ func NewSystemHandler(cfg *config.Config,
taskInspector: taskInspector,
knowledgeSvc: knowledgeSvc,
storageBackendRepo: storageBackendRepo,
+ sandboxConfigSvc: sandboxConfigSvc,
}
}
diff --git a/internal/im/tool_display.go b/internal/im/tool_display.go
index 204c7a7eb..778bbf072 100644
--- a/internal/im/tool_display.go
+++ b/internal/im/tool_display.go
@@ -49,6 +49,7 @@ var imToolNameLabels = map[string]string{
"query_knowledge_graph": "知识图谱查询",
"read_skill": "读取技能",
"execute_skill_script": "执行技能脚本",
+ "shell_exec": "执行沙箱命令",
"data_analysis": "数据分析",
"data_schema": "数据结构",
"database_query": "数据库查询",
diff --git a/internal/logger/logger.go b/internal/logger/logger.go
index 6cf9d1d9c..a3ee98513 100644
--- a/internal/logger/logger.go
+++ b/internal/logger/logger.go
@@ -526,6 +526,13 @@ func CloneContext(ctx context.Context) context.Context {
types.SystemAdminContextKey,
types.LanguageContextKey,
types.SessionTenantIDContextKey,
+ types.SessionIDContextKey,
+ // SandboxTenantIDContextKey: the session owner's tenant, which the
+ // shared-agent path deliberately keeps separate from
+ // TenantIDContextKey. Dropping it here would silently re-key every
+ // session→sandbox binding onto the borrowed tenant, because
+ // setupSSEStream builds its async context through CloneContext.
+ types.SandboxTenantIDContextKey,
types.EmbedQueryContextKey,
types.EmbedVisitorContextKey,
// Keep the Langfuse trace alive across CloneContext boundaries so
diff --git a/internal/logger/logger_test.go b/internal/logger/logger_test.go
index 841b2bb9a..9f1d31e64 100644
--- a/internal/logger/logger_test.go
+++ b/internal/logger/logger_test.go
@@ -212,3 +212,22 @@ func TestCloneContextPreservesTenantAPIKeyScope(t *testing.T) {
t.Fatalf("cloned scope = %#v, want key_id=7 scoped to kb-1", got)
}
}
+
+// setupSSEStream builds its async context through CloneContext, so dropping
+// this key here would silently re-key every session→sandbox binding onto the
+// tenant a shared agent borrowed — stranding the MicroVM at session deletion.
+func TestCloneContextPreservesSandboxTenantID(t *testing.T) {
+ t.Parallel()
+
+ const sessionOwner, agentOwner = uint64(7), uint64(99)
+
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, agentOwner)
+ ctx = types.WithSandboxTenantID(ctx, sessionOwner)
+ cloned := CloneContext(ctx)
+
+ got, ok := types.SandboxTenantIDFromContext(cloned)
+ if !ok || got != sessionOwner {
+ t.Fatalf("SandboxTenantIDFromContext(cloned) = (%d, %v), want (%d, true)",
+ got, ok, sessionOwner)
+ }
+}
diff --git a/internal/modelcontext/tool_policy.go b/internal/modelcontext/tool_policy.go
index 867a64ef4..1fb179452 100644
--- a/internal/modelcontext/tool_policy.go
+++ b/internal/modelcontext/tool_policy.go
@@ -144,6 +144,11 @@ var toolHandlePolicies = map[string]toolHandlePolicy{
// "url"/"knowledge_id" with unrelated semantics.
"read_skill": {},
"execute_skill_script": {},
+ // Sandbox shell/file tools return whatever a skill script produced, so they
+ // carry the same unknown-shape caveat as skill output above.
+ "shell_exec": {},
+ "list_sandbox_files": {},
+ "read_sandbox_file": {},
}
// HasToolPolicy reports whether a tool has an explicit model-handle policy.
diff --git a/internal/router/router.go b/internal/router/router.go
index cc9b11368..cd5ba6ed2 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -56,6 +56,7 @@ type RouterParams struct {
MessageSuggestionHandler *handler.MessageSuggestionHandler
ModelHandler *handler.ModelHandler
ModelCredentialsHandler *handler.ModelCredentialsHandler
+ SandboxConfigHandler *handler.SandboxConfigHandler
EvaluationHandler *handler.EvaluationHandler
AuthHandler *handler.AuthHandler
InitializationHandler *handler.InitializationHandler
@@ -262,6 +263,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterChatRoutes(v1, params.SessionHandler, rbacGuards)
RegisterMessageRoutes(v1, params.MessageHandler, rbacGuards)
RegisterModelRoutes(v1, params.ModelHandler, params.ModelCredentialsHandler, rbacGuards)
+ RegisterSandboxConfigRoutes(v1, params.SandboxConfigHandler, rbacGuards)
RegisterEvaluationRoutes(v1, params.EvaluationHandler, rbacGuards)
RegisterInitializationRoutes(v1, params.InitializationHandler, rbacGuards)
RegisterSystemRoutes(v1, params.SystemHandler, rbacGuards)
diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go
index 5127a6064..3fd151c28 100644
--- a/internal/router/router_api_key_capabilities_test.go
+++ b/internal/router/router_api_key_capabilities_test.go
@@ -342,6 +342,7 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
RegisterWebSearchProviderRoutes(v1, &handler.WebSearchProviderHandler{}, &handler.WebSearchProviderCredentialsHandler{}, g)
RegisterVectorStoreRoutes(v1, &handler.VectorStoreHandler{}, g)
RegisterStorageBackendRoutes(v1, &handler.StorageBackendHandler{}, g)
+ RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, g)
RegisterEmbedChannelRoutes(v1, &handler.EmbedChannelHandler{}, g)
RegisterIMChannelRoutes(v1, &handler.IMHandler{}, g)
RegisterDataSourceRoutes(v1, &handler.DataSourceHandler{}, &handler.DataSourceCredentialsHandler{}, g)
@@ -379,6 +380,38 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
}
}
+func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodGet, "/api/v1/sandbox-configs"},
+ {http.MethodPost, "/api/v1/sandbox-configs"},
+ {http.MethodGet, "/api/v1/sandbox-configs/:id"},
+ {http.MethodPut, "/api/v1/sandbox-configs/:id"},
+ {http.MethodDelete, "/api/v1/sandbox-configs/:id"},
+ {http.MethodGet, "/api/v1/sandbox-configs/:id/sandboxes"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.method+" "+tc.path, func(t *testing.T) {
+ policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
+ if !policy.RequireFullAccess {
+ t.Fatal("sandbox config routes should require full access")
+ }
+ if len(policy.Capabilities) != 0 {
+ t.Fatalf("sandbox config routes must not be granted by a scoped capability: %#v", policy.Capabilities)
+ }
+ })
+ }
+}
+
func TestTenantMemberRoutesDeclareManageMembersCapability(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
diff --git a/internal/router/routes_auth_tenant.go b/internal/router/routes_auth_tenant.go
index 3484d25bb..86c9c44b1 100644
--- a/internal/router/routes_auth_tenant.go
+++ b/internal/router/routes_auth_tenant.go
@@ -220,6 +220,7 @@ func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g
systemRoutes.POST("/docreader/reconnect", g.Admin(), handler.ReconnectDocReader)
systemRoutes.GET("/storage-engine-status", g.Viewer(), handler.GetStorageEngineStatus)
systemRoutes.POST("/storage-engine-check", g.Admin(), handler.CheckStorageEngine)
+ systemRoutes.POST("/sandbox-check", g.Admin(), handler.CheckSandboxConfig)
}
}
diff --git a/internal/router/routes_chat.go b/internal/router/routes_chat.go
index dfd23af17..8cd2cc78c 100644
--- a/internal/router/routes_chat.go
+++ b/internal/router/routes_chat.go
@@ -79,6 +79,21 @@ func RegisterSessionRoutes(
sessions.POST("/:session_id/messages/:message_id/suggestions", suggestionHandler.Ensure)
sessions.POST("/:session_id/suggestion-events", suggestionHandler.RecordEvent)
}
+
+ // Skill-generated file artifacts. The list endpoints only expose
+ // metadata; the actual bytes are streamed via /artifacts/:index/download
+ // so the storage URL never appears on the wire.
+ //
+ // NOTE: gin builds a separate radix tree per HTTP verb but every
+ // path in the same tree must share the same wildcard name. The GET
+ // tree already binds :id via /sessions/:id (GetSession); reusing
+ // :id here (instead of :session_id) avoids the
+ // "wildcard conflicts" panic at route registration. The handlers
+ // read the URL param via c.Param("session_id") with a fallback to
+ // c.Param("id") for exactly this reason.
+ sessions.GET("/:id/artifacts", handler.ListSessionArtifacts)
+ sessions.GET("/:id/messages/:message_id/artifacts", handler.ListMessageArtifacts)
+ sessions.GET("/:id/messages/:message_id/artifacts/:index/download", handler.DownloadMessageArtifact)
}
}
diff --git a/internal/router/routes_infra.go b/internal/router/routes_infra.go
index 784d2a5f2..98aaea1a4 100644
--- a/internal/router/routes_infra.go
+++ b/internal/router/routes_infra.go
@@ -40,6 +40,26 @@ func RegisterModelRoutes(
}
}
+// Sandbox configs are workspace infrastructure that hold provider credentials.
+// Scoped API keys cannot safely receive partial authority over them yet because
+// mutation can strand remote sandboxes.
+func RegisterSandboxConfigRoutes(
+ r *gin.RouterGroup,
+ h *handler.SandboxConfigHandler,
+ g *rbacGuards,
+) {
+ configs := g.apiKeyGroup(r.Group("/sandbox-configs"), apiKeyFullAccess())
+ {
+ configs.GET("", g.Viewer(), h.List)
+ configs.PUT("/workspace-policy", g.Admin(), h.SetWorkspacePolicy)
+ configs.POST("", g.Admin(), h.Create)
+ configs.GET("/:id", g.Viewer(), h.Get)
+ configs.PUT("/:id", g.Admin(), h.Update)
+ configs.DELETE("/:id", g.Admin(), h.Delete)
+ configs.GET("/:id/sandboxes", g.Admin(), h.Inventory)
+ }
+}
+
// RegisterEvaluationRoutes registers evaluation endpoints. Running an
// evaluation drives LLM calls (cost) and reads from KBs across the
// tenant; gate to Admin+ until product asks for a finer-grained
diff --git a/internal/sandbox/capabilities.go b/internal/sandbox/capabilities.go
new file mode 100644
index 000000000..95fbdf656
--- /dev/null
+++ b/internal/sandbox/capabilities.go
@@ -0,0 +1,81 @@
+// Package sandbox: session-scoped capability interfaces.
+//
+// The Sandbox / Manager pair intentionally hides provider identity (Cube,
+// E2B, Docker, Local) from the application layer. Higher layers should never
+// branch on Manager.GetType() to decide whether a feature is supported —
+// that couples them to a specific backend and, worse, misfires when a
+// remote-capable manager transparently falls back to a stateless local
+// sandbox.
+//
+// Instead, session-scoped features (shell execution, per-session file
+// inspection, attachment staging) are advertised via the capability
+// interfaces below. A manager may satisfy the underlying methods yet still
+// return nil from the accessors on SessionCapabilityProvider when the
+// current runtime configuration cannot honour that capability — for
+// example, SessionBoundManager returns nil from every accessor after it
+// falls back to LocalSandbox, ensuring the agent never surfaces
+// tenant-isolated tools that would run on the WeKnora host.
+package sandbox
+
+import (
+ "context"
+ "time"
+)
+
+// 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.
+type SessionShellExecutor interface {
+ ExecShellCommand(
+ ctx context.Context,
+ sessionID string,
+ command string,
+ workDir string,
+ timeout time.Duration,
+ env map[string]string,
+ ) (*ExecuteResult, error)
+}
+
+// SessionFileStore is the effective per-session filesystem view a manager
+// offers callers that need to inspect, stage, or clean up files inside the
+// session's remote sandbox. It is intentionally provider-neutral: entries
+// use RemoteDirEntry / RemoteStatEntry, so E2B and Cube can implement it
+// without touching the caller.
+type SessionFileStore interface {
+ // EnsureSessionDir creates dir in the session's live sandbox. Silent
+ // no-op when no sandbox is bound yet; the next Execute call will
+ // materialise the directory during script upload.
+ EnsureSessionDir(ctx context.Context, sessionID, dir string) error
+
+ // ListSessionFiles walks dir recursively and returns file entries.
+ // Returns nil (no error) when the session has no live sandbox so
+ // callers can treat "no sandbox" and "empty output" uniformly.
+ ListSessionFiles(ctx context.Context, sessionID, dir string) ([]RemoteDirEntry, error)
+
+ // StatSessionFile returns metadata for a single file. Errors when the
+ // session has no bound sandbox — callers of this method already hold a
+ // path from a prior ListSessionFiles call.
+ StatSessionFile(ctx context.Context, sessionID, path string) (*RemoteStatEntry, error)
+
+ // ReadSessionFile downloads a file's contents. Same "no sandbox
+ // bound" contract as StatSessionFile.
+ ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
+
+ // WriteSessionInputFile writes a durable attachment path into the
+ // session's remote sandbox, provisioning the sandbox on first call.
+ WriteSessionInputFile(ctx context.Context, sessionID, filePath string, content []byte) error
+
+ // RemoveSessionInputPath deletes a staged attachment. No-op when the
+ // session has no live sandbox.
+ RemoveSessionInputPath(ctx context.Context, sessionID, targetPath string) error
+}
+
+// SessionCapabilityProvider is implemented by managers that MAY offer
+// session-scoped capabilities. Accessors return nil when the current
+// runtime configuration cannot support that capability (e.g. remote
+// provider unhealthy → LocalSandbox fallback). Application code should
+// gate feature registration on non-nil accessor returns.
+type SessionCapabilityProvider interface {
+ SessionShellExecutor() SessionShellExecutor
+ SessionFileStore() SessionFileStore
+}
diff --git a/internal/sandbox/check_client_guard_test.go b/internal/sandbox/check_client_guard_test.go
new file mode 100644
index 000000000..154eb49de
--- /dev/null
+++ b/internal/sandbox/check_client_guard_test.go
@@ -0,0 +1,62 @@
+package sandbox
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// The connectivity probe dials endpoints an admin typed into an unsaved form,
+// so it is the one client whose target is fully attacker-influenced within a
+// workspace. Save-time validation cannot cover it: a hostname can resolve to a
+// public address while the form is validated and to the cloud metadata service
+// by the time the probe connects. Both providers must therefore refuse
+// link-local at dial time, and they must do so even under the private-endpoint
+// opt-in that self-hosted Cube deployments need.
+func TestNewRemoteClientForCheckRefusesLinkLocalAtDial(t *testing.T) {
+ // The opt-in is deliberately ON: link-local must stay blocked regardless.
+ t.Setenv(AllowPrivateEndpointsEnv, "true")
+
+ const metadata = "http://169.254.169.254"
+
+ for _, tc := range []struct {
+ name string
+ cfg *Config
+ }{
+ {
+ name: "cube",
+ cfg: &Config{
+ Type: SandboxTypeCube,
+ CubeAPIURL: metadata,
+ CubeProxyURL: metadata,
+ CubeSandboxDomain: "cube.app",
+ CubeTemplate: "tpl-test",
+ },
+ },
+ {
+ name: "e2b",
+ cfg: &Config{
+ Type: SandboxTypeE2B,
+ E2BAPIKey: "key-test",
+ E2BAPIURL: metadata,
+ E2BTemplate: "base",
+ },
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ client, err := NewRemoteClientForCheck(tc.cfg)
+ require.NoError(t, err)
+
+ err = client.Health(context.Background())
+ require.Error(t, err, "probing the metadata service must fail")
+ // The guard rejects before any packet leaves, so the refusal - not
+ // a connection timeout - is what has to surface.
+ require.True(t,
+ strings.Contains(err.Error(), ErrUnsafeOutboundURL.Error()) ||
+ strings.Contains(err.Error(), "never routable"),
+ "expected the outbound guard to refuse the dial, got: %v", err)
+ })
+ }
+}
diff --git a/internal/sandbox/config_defaults.go b/internal/sandbox/config_defaults.go
new file mode 100644
index 000000000..9828b497f
--- /dev/null
+++ b/internal/sandbox/config_defaults.go
@@ -0,0 +1,65 @@
+// Package sandbox: description of the process-wide defaults a tenant inherits.
+//
+// A tenant that has not overridden a field runs on the deployment's global
+// WEKNORA_SANDBOX_* configuration. The settings UI has to show what is actually
+// in effect, otherwise an empty override set looks indistinguishable from
+// "disabled" — and saving that impression would silently disable the sandbox.
+//
+// Secrets are deliberately never included here; only whether one is present.
+package sandbox
+
+// ProviderDefaults is the inheritable, non-secret configuration of one backend.
+type ProviderDefaults struct {
+ APIURL string `json:"api_url,omitempty"`
+ ProxyURL string `json:"proxy_url,omitempty"`
+ SandboxDomain string `json:"sandbox_domain,omitempty"`
+ TemplateID string `json:"template_id,omitempty"`
+ APIKeyConfigured bool `json:"api_key_configured"`
+ HTTPTimeoutSec int `json:"http_timeout_sec,omitempty"`
+ SandboxTTLSec int `json:"sandbox_ttl_seconds,omitempty"`
+}
+
+// ConfigDefaults mirrors types.TenantSandboxConfig's shape so the UI can render
+// inherited values as placeholders next to the tenant's own overrides.
+type ConfigDefaults struct {
+ // SandboxType is the backend a tenant gets when it sets no override.
+ SandboxType string `json:"sandbox_type"`
+ DefaultTimeoutSec int `json:"default_timeout_sec,omitempty"`
+ DockerImage string `json:"docker_image,omitempty"`
+ Cube *ProviderDefaults `json:"cube,omitempty"`
+ E2B *ProviderDefaults `json:"e2b,omitempty"`
+}
+
+// DescribeDefaults projects a resolved global Config into its inheritable,
+// secret-free description.
+func DescribeDefaults(cfg *Config) *ConfigDefaults {
+ if cfg == nil {
+ return &ConfigDefaults{SandboxType: string(SandboxTypeDisabled)}
+ }
+ defaults := &ConfigDefaults{
+ SandboxType: string(cfg.Type),
+ DefaultTimeoutSec: int(cfg.DefaultTimeout.Seconds()),
+ DockerImage: cfg.DockerImage,
+ }
+ // Describe both remote backends regardless of the active mode: an admin
+ // switching a workspace to the other one still needs to see what it would
+ // inherit.
+ defaults.Cube = &ProviderDefaults{
+ APIURL: cfg.CubeAPIURL,
+ ProxyURL: cfg.CubeProxyURL,
+ SandboxDomain: cfg.CubeSandboxDomain,
+ TemplateID: cfg.CubeTemplate,
+ APIKeyConfigured: cfg.CubeAPIKey != "",
+ HTTPTimeoutSec: int(cfg.CubeHTTPTimeout.Seconds()),
+ SandboxTTLSec: int(cfg.CubeSandboxTTL.Seconds()),
+ }
+ defaults.E2B = &ProviderDefaults{
+ APIURL: cfg.E2BAPIURL,
+ SandboxDomain: cfg.E2BSandboxDomain,
+ TemplateID: cfg.E2BTemplate,
+ APIKeyConfigured: cfg.E2BAPIKey != "",
+ HTTPTimeoutSec: int(cfg.E2BHTTPTimeout.Seconds()),
+ SandboxTTLSec: int(cfg.E2BSandboxTTL.Seconds()),
+ }
+ return defaults
+}
diff --git a/internal/sandbox/config_identity.go b/internal/sandbox/config_identity.go
new file mode 100644
index 000000000..38634598d
--- /dev/null
+++ b/internal/sandbox/config_identity.go
@@ -0,0 +1,71 @@
+// Package sandbox: what makes an existing sandbox operable.
+//
+// Two groups of configuration fields decide whether the sandboxes a config has
+// already created can still be acted on. This file names them in one place
+// because the answer depends on which SDK carries which value:
+//
+// - Control plane (API URL, API key): every lifecycle call - list, delete,
+// pause, resume, refresh timeout - is issued against it. Lose it and the
+// sandboxes can no longer be reclaimed at all.
+// - Data plane (sandbox domain, and for Cube the proxy endpoint): envd traffic
+// is routed through it. Lose it and the sandboxes are still deletable but no
+// longer usable, so every live session on the config fails at once.
+//
+// The split is a property of the clients in use, not a universal truth:
+// github.com/matiasinsaurralde/go-e2b resolves the API base URL and the sandbox
+// domain independently, whereas E2B's own JS/Python SDKs derive the API base from
+// the domain (https://api.${domain}). Swapping that dependency would move the
+// domain into the control-plane group.
+package sandbox
+
+import (
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// SandboxIdentity is the comparable projection of a config: two configs with
+// equal identities can operate each other's sandboxes.
+type SandboxIdentity struct {
+ Provider string
+
+ // Control plane - whether an existing sandbox can still be reclaimed.
+ APIURL string
+ APIKey string
+
+ // Data plane - whether an existing sandbox can still be used.
+ SandboxDomain string
+ ProxyURL string
+}
+
+// IdentityOf projects a stored config onto its identity. Only the active
+// provider's fields are read: a sub-struct left behind by an earlier provider
+// switch says nothing about where today's sandboxes live.
+//
+// Because named configs inherit nothing, the stored row is the whole picture and
+// no deployment baseline is consulted. Unknown type strings are compared verbatim
+// rather than rejected: a typo yields an identity that matches nothing, which
+// errs toward refusing the edit, and ParseSandboxType reports it on save.
+//
+// This runs no SSRF guard and returns no error on purpose. It answers "would this
+// edit strand anything", a question that must stay answerable when the OLD
+// endpoint no longer resolves — precisely the situation in which an admin needs
+// to re-point the config. Validating the incoming URLs is the save path's job.
+func IdentityOf(tenantCfg *types.TenantSandboxConfig) SandboxIdentity {
+ if tenantCfg == nil {
+ return SandboxIdentity{}
+ }
+ identity := SandboxIdentity{Provider: tenantCfg.SandboxType}
+ switch SandboxType(tenantCfg.SandboxType) {
+ case SandboxTypeCube:
+ if cube := tenantCfg.Cube; cube != nil {
+ identity.APIURL, identity.APIKey = cube.APIURL, cube.APIKey
+ identity.SandboxDomain = cube.SandboxDomain
+ identity.ProxyURL = cube.ProxyURL
+ }
+ case SandboxTypeE2B:
+ if e2bCfg := tenantCfg.E2B; e2bCfg != nil {
+ identity.APIURL, identity.APIKey = e2bCfg.APIURL, e2bCfg.APIKey
+ identity.SandboxDomain = e2bCfg.SandboxDomain
+ }
+ }
+ return identity
+}
diff --git a/internal/sandbox/config_identity_test.go b/internal/sandbox/config_identity_test.go
new file mode 100644
index 000000000..ab11f28b3
--- /dev/null
+++ b/internal/sandbox/config_identity_test.go
@@ -0,0 +1,75 @@
+package sandbox
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// Identity comes from the stored row alone. Nothing about the deployment can
+// change it, which is what makes "did this edit strand a sandbox" answerable
+// without reaching for WEKNORA_SANDBOX_*.
+func TestIdentityOfReadsStoredFieldsOnly(t *testing.T) {
+ identity := IdentityOf(&types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIURL: "https://api.e2b.app", SandboxDomain: "e2b.app", APIKey: "key-a",
+ },
+ })
+
+ require.Equal(t, SandboxIdentity{
+ Provider: "e2b",
+ APIURL: "https://api.e2b.app",
+ APIKey: "key-a",
+ SandboxDomain: "e2b.app",
+ }, identity)
+}
+
+// A blank field is blank, not "whatever the deployment runs". Two configs that
+// differ only in what they spell out are therefore different identities.
+func TestIdentityOfDoesNotInherit(t *testing.T) {
+ blank := IdentityOf(&types.TenantSandboxConfig{SandboxType: "cube"})
+ spelledOut := IdentityOf(&types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{
+ APIURL: DefaultCubeAPIURL, ProxyURL: DefaultCubeProxyURL,
+ SandboxDomain: DefaultCubeSandboxDomain,
+ },
+ })
+
+ require.Equal(t, SandboxIdentity{Provider: "cube"}, blank)
+ require.NotEqual(t, blank, spelledOut)
+ require.Equal(t, DefaultCubeProxyURL, spelledOut.ProxyURL)
+}
+
+// Only the active provider describes where the sandboxes are; the other
+// sub-struct is leftover state from an earlier switch.
+func TestIdentityOfReadsOnlyActiveProvider(t *testing.T) {
+ cfg := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIKey: "e2b-key"},
+ Cube: &types.CubeSandboxConfig{APIKey: "stale-cube-key"},
+ }
+
+ identity := IdentityOf(cfg)
+
+ require.Equal(t, "e2b-key", identity.APIKey)
+ require.Empty(t, identity.ProxyURL, "Cube's data plane is irrelevant while E2B is active")
+}
+
+// Backends that hold no remote resources carry no credentials, but switching
+// between them still has to register as a change.
+func TestIdentityOfLocalBackendsCarryProviderOnly(t *testing.T) {
+ docker := IdentityOf(&types.TenantSandboxConfig{SandboxType: "docker"})
+ local := IdentityOf(&types.TenantSandboxConfig{SandboxType: "local"})
+
+ require.Equal(t, SandboxIdentity{Provider: "docker"}, docker)
+ require.NotEqual(t, docker, local)
+}
+
+// A nil config must not panic: Update compares against it when creating.
+func TestIdentityOfToleratesNilConfig(t *testing.T) {
+ require.Equal(t, SandboxIdentity{}, IdentityOf(nil))
+}
diff --git a/internal/sandbox/config_required.go b/internal/sandbox/config_required.go
new file mode 100644
index 000000000..49b9f501a
--- /dev/null
+++ b/internal/sandbox/config_required.go
@@ -0,0 +1,77 @@
+// Package sandbox: what a named backend config must carry on its own.
+//
+// A named config is self-contained. Nothing is inherited from the deployment
+// WEKNORA_SANDBOX_* baseline, which exists only to serve agents that selected no
+// config at all. The trade for that clarity is that every value the provider
+// client cannot synthesize has to be present in the config itself, so this file
+// names those values once and both the save path and the resolve path check
+// against it.
+//
+// Two classes are deliberately NOT required:
+//
+// - Credentials a self-hosted deployment does not use. The common single-node
+// Cube setup runs unauthenticated, so CubeAPIKey stays optional.
+// - Values the SDK resolves by itself. go-e2b defaults both the API base URL
+// and the sandbox domain when they are left empty, so demanding them would
+// force operators to spell out constants they cannot verify.
+//
+// Everything else is required precisely because its absence fails late and
+// obscurely: a missing Cube proxy URL or sandbox domain still creates a sandbox
+// and only breaks when envd traffic is routed, which reads as a provider outage
+// rather than a typo in the form.
+package sandbox
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+)
+
+// ErrSandboxConfigIncomplete marks a named config that cannot build a working
+// client because required fields are empty. Callers map it onto 400.
+var ErrSandboxConfigIncomplete = errors.New("sandbox: config is missing required fields")
+
+// MissingRequiredFields lists the fields cfg fails to supply for its own
+// provider, named after the JSON keys the API and the settings form use so the
+// message can be surfaced without translation. Backends that hold no endpoint
+// of their own (docker / local / disabled) require nothing.
+func MissingRequiredFields(cfg *Config) []string {
+ if cfg == nil {
+ return nil
+ }
+ var missing []string
+ require := func(field, value string) {
+ if strings.TrimSpace(value) == "" {
+ missing = append(missing, field)
+ }
+ }
+ switch cfg.Type {
+ case SandboxTypeCube:
+ require("api_url", cfg.CubeAPIURL)
+ require("proxy_url", cfg.CubeProxyURL)
+ require("sandbox_domain", cfg.CubeSandboxDomain)
+ require("template_id", cfg.CubeTemplate)
+ case SandboxTypeE2B:
+ require("api_key", cfg.E2BAPIKey)
+ require("template_id", cfg.E2BTemplate)
+ }
+ return missing
+}
+
+// RequireCompleteConfig is the error form of MissingRequiredFields, shared by
+// the save path and the resolve path so both reject the same configs with the
+// same wording.
+func RequireCompleteConfig(cfg *Config) error {
+ missing := MissingRequiredFields(cfg)
+ if len(missing) == 0 {
+ return nil
+ }
+ provider := ""
+ if cfg != nil {
+ provider = string(cfg.Type)
+ }
+ return fmt.Errorf(
+ "%w: %s backend requires %s",
+ ErrSandboxConfigIncomplete, provider, strings.Join(missing, ", "),
+ )
+}
diff --git a/internal/sandbox/config_sandboxes.go b/internal/sandbox/config_sandboxes.go
new file mode 100644
index 000000000..0f57a77ae
--- /dev/null
+++ b/internal/sandbox/config_sandboxes.go
@@ -0,0 +1,114 @@
+// Package sandbox: per-config sandbox inventory.
+//
+// Identity changes (provider / endpoint / API key) and config deletion both
+// need one question answered authoritatively: does this config still own live
+// sandboxes on the provider?
+//
+// The binding store cannot answer it. Bindings go missing exactly when leaks
+// happen - a CAS rebind overwrites the old sandbox ID, Redis evicts, a process
+// restarts - so trusting them under-reports in the one direction that costs
+// money. The provider's own listing is the source of truth.
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// ConfigSandboxLister is the read half of the provider client.
+type ConfigSandboxLister interface {
+ List(ctx context.Context, filter RemoteListFilter) ([]RemoteSandboxSummary, error)
+}
+
+// ConfigSandboxClient adds deletion, needed to release an inventory.
+type ConfigSandboxClient interface {
+ ConfigSandboxLister
+ Delete(ctx context.Context, sandboxID string) error
+}
+
+// NormalizeConfigID maps the empty config ID onto the sentinel used in
+// metadata, so "the deployment default config" is addressable like any other.
+func NormalizeConfigID(configID string) string {
+ if strings.TrimSpace(configID) == "" {
+ return types.SandboxConfigIDGlobalDefault
+ }
+ return configID
+}
+
+// MetadataSessionIDKey returns the provider metadata key used for session IDs.
+func MetadataSessionIDKey() string {
+ return remoteMetadataSessionID
+}
+
+// configSandboxFilter narrows a listing to one workspace's one config.
+func configSandboxFilter(tenantID uint64, configID string) RemoteListFilter {
+ return RemoteListFilter{
+ Metadata: map[string]string{
+ remoteMetadataTenantID: strconv.FormatUint(tenantID, 10),
+ remoteMetadataConfigID: NormalizeConfigID(configID),
+ },
+ // Paused sandboxes are not idle leftovers: they bill, and a session
+ // expects to resume them. Omitting them would report "nothing here"
+ // right before the credentials that could delete them are replaced.
+ States: []RemoteSandboxState{RemoteStateRunning, RemoteStatePaused},
+ }
+}
+
+// ListConfigSandboxes returns the sandboxes a config currently owns.
+func ListConfigSandboxes(
+ ctx context.Context,
+ client ConfigSandboxLister,
+ tenantID uint64,
+ configID string,
+) ([]RemoteSandboxSummary, error) {
+ if client == nil {
+ return nil, fmt.Errorf("sandbox: listing requires a client")
+ }
+ summaries, err := client.List(ctx, configSandboxFilter(tenantID, configID))
+ if err != nil {
+ return nil, fmt.Errorf(
+ "sandbox: list workspace %d config %q sandboxes: %w",
+ tenantID, NormalizeConfigID(configID), err)
+ }
+ return summaries, nil
+}
+
+// ReleaseConfigSandboxes deletes every sandbox the config owns and reports how
+// many went away.
+//
+// This is deliberately NOT exposed as an admin action. Its one caller is the
+// sweep that runs immediately after a config's credentials are overwritten,
+// using the outgoing credentials still held in memory — the only remaining
+// moment those sandboxes can be reached at all. An admin blocked from editing a
+// config is instead told to end the owning sessions or create a second config.
+//
+// One undeletable sandbox does not abort the sweep - partial progress is
+// strictly better than none - but the failures ARE returned. Swallowing them
+// would leave a paused instance billing on credentials that no longer exist
+// anywhere, with no record of which sandbox it was.
+func ReleaseConfigSandboxes(
+ ctx context.Context,
+ client ConfigSandboxClient,
+ tenantID uint64,
+ configID string,
+) (int, error) {
+ summaries, err := ListConfigSandboxes(ctx, client, tenantID, configID)
+ if err != nil {
+ return 0, err
+ }
+ deleted := 0
+ var failures []error
+ for _, summary := range summaries {
+ if err := client.Delete(ctx, summary.ID); err != nil {
+ failures = append(failures, fmt.Errorf("delete sandbox %s: %w", summary.ID, err))
+ continue
+ }
+ deleted++
+ }
+ return deleted, errors.Join(failures...)
+}
diff --git a/internal/sandbox/config_sandboxes_test.go b/internal/sandbox/config_sandboxes_test.go
new file mode 100644
index 000000000..ed34c60ac
--- /dev/null
+++ b/internal/sandbox/config_sandboxes_test.go
@@ -0,0 +1,126 @@
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// fakeConfigSandboxClient records the filters it was asked for and serves a
+// fixed inventory, so the test can assert both the query and the deletions.
+type fakeConfigSandboxClient struct {
+ inventory []RemoteSandboxSummary
+ filters []RemoteListFilter
+ deleted []string
+ deleteFailures map[string]error
+}
+
+func (f *fakeConfigSandboxClient) List(
+ _ context.Context, filter RemoteListFilter,
+) ([]RemoteSandboxSummary, error) {
+ f.filters = append(f.filters, filter)
+ var out []RemoteSandboxSummary
+ for _, s := range f.inventory {
+ match := true
+ for k, v := range filter.Metadata {
+ if s.Metadata[k] != v {
+ match = false
+ break
+ }
+ }
+ if match {
+ out = append(out, s)
+ }
+ }
+ return out, nil
+}
+
+func (f *fakeConfigSandboxClient) Delete(_ context.Context, sandboxID string) error {
+ if err := f.deleteFailures[sandboxID]; err != nil {
+ return err
+ }
+ f.deleted = append(f.deleted, sandboxID)
+ return nil
+}
+
+func summary(id, tenant, config string) RemoteSandboxSummary {
+ return RemoteSandboxSummary{
+ ID: id,
+ Metadata: map[string]string{
+ remoteMetadataTenantID: tenant,
+ remoteMetadataConfigID: config,
+ },
+ }
+}
+
+func TestListConfigSandboxesIncludesPausedAndScopesToConfig(t *testing.T) {
+ client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
+ summary("sb-1", "7", "cfg-a"),
+ summary("sb-2", "7", "cfg-b"),
+ summary("sb-3", "8", "cfg-a"),
+ }}
+
+ got, err := ListConfigSandboxes(context.Background(), client, 7, "cfg-a")
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+ require.Equal(t, "sb-1", got[0].ID)
+
+ require.Len(t, client.filters, 1)
+ require.Equal(t, "cfg-a", client.filters[0].Metadata[remoteMetadataConfigID])
+ require.Equal(t, "7", client.filters[0].Metadata[remoteMetadataTenantID])
+ require.ElementsMatch(t,
+ []RemoteSandboxState{RemoteStateRunning, RemoteStatePaused},
+ client.filters[0].States,
+ "paused sandboxes still bill and are what a session expects to resume")
+}
+
+func TestListConfigSandboxesUsesSentinelForGlobalDefault(t *testing.T) {
+ client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
+ summary("sb-1", "7", types.SandboxConfigIDGlobalDefault),
+ }}
+
+ got, err := ListConfigSandboxes(context.Background(), client, 7, "")
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+}
+
+func TestMetadataSessionIDKeyReturnsSessionMetadataKey(t *testing.T) {
+ require.Equal(t, remoteMetadataSessionID, MetadataSessionIDKey())
+}
+
+// Releasing one config must not touch a sibling config that happens to use the
+// same provider account.
+func TestReleaseConfigSandboxesLeavesSiblingConfigAlone(t *testing.T) {
+ client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
+ summary("sb-1", "7", "cfg-a"),
+ summary("sb-2", "7", "cfg-b"),
+ }}
+
+ deleted, err := ReleaseConfigSandboxes(context.Background(), client, 7, "cfg-a")
+ require.NoError(t, err)
+ require.Equal(t, 1, deleted)
+ require.Equal(t, []string{"sb-1"}, client.deleted)
+}
+
+func TestReleaseConfigSandboxesContinuesAndReturnsDeleteFailures(t *testing.T) {
+ client := &fakeConfigSandboxClient{
+ inventory: []RemoteSandboxSummary{
+ summary("sb-1", "7", "cfg-a"),
+ summary("sb-2", "7", "cfg-a"),
+ summary("sb-3", "7", "cfg-a"),
+ },
+ deleteFailures: map[string]error{
+ "sb-2": errors.New("provider delete failed"),
+ },
+ }
+
+ deleted, err := ReleaseConfigSandboxes(context.Background(), client, 7, "cfg-a")
+ require.Error(t, err)
+ require.ErrorContains(t, err, "sb-2")
+ require.Equal(t, 2, deleted)
+ require.Equal(t, []string{"sb-1", "sb-3"}, client.deleted)
+}
diff --git a/internal/sandbox/cube_integration_test.go b/internal/sandbox/cube_integration_test.go
new file mode 100644
index 000000000..27f14f88c
--- /dev/null
+++ b/internal/sandbox/cube_integration_test.go
@@ -0,0 +1,582 @@
+//go:build integration
+
+// Package sandbox integration tests against a locally-running CubeSandbox
+// deployment. These tests DO NOT use any mock — they connect straight to a
+// live CubeAPI + CubeProxy pair. Enable them with the `integration` build tag:
+//
+// CUBE_API_URL=http://127.0.0.1:33000 \
+// CUBE_PROXY_URL=http://127.0.0.1:12088 \
+// go test -tags=integration -run Integration -count=1 ./internal/sandbox/...
+//
+// If the environment variables are unset the tests fall back to the local
+// dev defaults (127.0.0.1:33000 for the CubeAPI, 127.0.0.1:80 for the
+// CubeProxy). A ready template is auto-discovered from /templates unless
+// CUBE_TEMPLATE_ID is supplied.
+//
+// Every test hands its sandboxes back through Cleanup / Delete, so a
+// clean run should leave no live MicroVMs behind.
+package sandbox
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+const (
+ // integrationDefaultAPIURL / integrationDefaultProxyURL match the user's
+ // local Cube deployment: CubeAPI on 33000, CubeProxy (openresty inside
+ // the cube-proxy docker container) on the host's port 80. The Dashboard
+ // (cube-webui) is exposed on 12088 and MUST NOT be used as a data-plane
+ // endpoint — POST requests against it return 405 because Dashboard is a
+ // static SPA server, not a routing proxy.
+ integrationDefaultAPIURL = "http://127.0.0.1:33000"
+ integrationDefaultProxyURL = "http://127.0.0.1:80"
+
+ integrationSandboxTTL = 5 * time.Minute
+ integrationHTTPTimeout = 30 * time.Second
+ integrationDefaultExecTimeout = 60 * time.Second
+)
+
+// integrationConfig builds a Config suitable for talking to the on-host Cube
+// deployment. It probes /templates so tests survive template ID rotations,
+// and applies short timeouts so a broken environment fails loudly instead of
+// hanging.
+func integrationConfig(t *testing.T) *Config {
+ t.Helper()
+ cfg := DefaultConfig()
+ cfg.Type = SandboxTypeCube
+ cfg.FallbackEnabled = false
+
+ if v := strings.TrimSpace(os.Getenv("CUBE_API_URL")); v != "" {
+ cfg.CubeAPIURL = v
+ } else {
+ cfg.CubeAPIURL = integrationDefaultAPIURL
+ }
+ if v := strings.TrimSpace(os.Getenv("CUBE_PROXY_URL")); v != "" {
+ cfg.CubeProxyURL = v
+ } else {
+ cfg.CubeProxyURL = integrationDefaultProxyURL
+ }
+ cfg.CubeSandboxDomain = DefaultCubeSandboxDomain
+ cfg.CubeHTTPTimeout = integrationHTTPTimeout
+ cfg.CubeSandboxTTL = integrationSandboxTTL
+ cfg.DefaultTimeout = integrationDefaultExecTimeout
+
+ if v := strings.TrimSpace(os.Getenv("CUBE_TEMPLATE_ID")); v != "" {
+ cfg.CubeTemplate = v
+ } else {
+ cfg.CubeTemplate = discoverReadyTemplate(t, cfg.CubeAPIURL, cfg.CubeAPIKey)
+ }
+
+ t.Logf("Cube integration target api=%s proxy=%s template=%s domain=%s",
+ cfg.CubeAPIURL, cfg.CubeProxyURL, cfg.CubeTemplate, cfg.CubeSandboxDomain)
+ return cfg
+}
+
+// discoverReadyTemplate mirrors what the SDK's own integration suite does:
+// pick the first READY template from the CubeAPI /templates listing so
+// developers don't have to hard-code a template ID for local runs.
+func discoverReadyTemplate(t *testing.T, apiURL, apiKey string) string {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(apiURL, "/")+"/templates", nil)
+ if err != nil {
+ t.Fatalf("build templates request: %v", err)
+ }
+ if apiKey != "" {
+ req.Header.Set("Authorization", "Bearer "+apiKey)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("list templates from %s: %v", apiURL, err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("list templates HTTP %d from %s", resp.StatusCode, apiURL)
+ }
+
+ var templates []struct {
+ TemplateID string `json:"templateID"`
+ Status string `json:"status"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&templates); err != nil {
+ t.Fatalf("decode templates: %v", err)
+ }
+ for _, tpl := range templates {
+ if tpl.TemplateID != "" && strings.EqualFold(tpl.Status, "READY") {
+ return tpl.TemplateID
+ }
+ }
+ if len(templates) > 0 && templates[0].TemplateID != "" {
+ return templates[0].TemplateID
+ }
+ t.Fatalf("no templates found at %s; set CUBE_TEMPLATE_ID", apiURL)
+ return ""
+}
+
+// writeIntegrationScript drops a small Python script in a t.TempDir() so
+// tests have a real filesystem path for ExecuteConfig.Script (the security
+// validator still needs to read the file even though the sandbox executes
+// the uploaded copy).
+func writeIntegrationScript(t *testing.T, name, body string) string {
+ t.Helper()
+ dir := t.TempDir()
+ p := dir + "/" + name
+ if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
+ t.Fatalf("write %s: %v", p, err)
+ }
+ return p
+}
+
+// -----------------------------------------------------------------------------
+// Client-level tests (CubeRemoteClient directly)
+// -----------------------------------------------------------------------------
+
+// TestIntegrationCubeClient_HealthAndList sanity-checks that the /health
+// endpoint responds and ListSandboxes deserialises. Failure here almost
+// always means CubeAPI isn't running on the expected port.
+func TestIntegrationCubeClient_HealthAndList(t *testing.T) {
+ cfg := integrationConfig(t)
+ client, err := NewCubeRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("NewCubeRemoteClient: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ if err := client.Health(ctx); err != nil {
+ t.Fatalf("Health: %v", err)
+ }
+ summaries, err := client.List(ctx, RemoteListFilter{})
+ if err != nil {
+ t.Fatalf("List: %v", err)
+ }
+ t.Logf("current live sandboxes: %d", len(summaries))
+}
+
+// TestIntegrationCubeClient_CreateConnectRoundTrip validates that Create +
+// Connect + Get form a consistent lifecycle round-trip through the real
+// CubeAPI. It replaces the old ConnectRoundTripRequiresTimeout test which
+// verified the SDK connect body patch — that patch is now handled internally
+// by CubeRemoteClient.
+func TestIntegrationCubeClient_CreateConnectRoundTrip(t *testing.T) {
+ cfg := integrationConfig(t)
+ client, err := NewCubeRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("NewCubeRemoteClient: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: cfg.CubeTemplate,
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: integrationSandboxTTL,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ sandboxID := handle.ID()
+ t.Logf("created sandbox %s", sandboxID)
+ t.Cleanup(func() {
+ cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := client.Delete(cleanupCtx, sandboxID); err != nil {
+ t.Logf("cleanup delete sandbox %s: %v", sandboxID, err)
+ }
+ })
+
+ // Verify the sandbox is immediately visible via Get.
+ summary, err := client.Get(ctx, sandboxID)
+ if err != nil {
+ t.Fatalf("Get after create: %v", err)
+ }
+ if summary == nil || summary.ID != sandboxID {
+ t.Fatalf("Get returned unexpected summary: %#v", summary)
+ }
+
+ // Reconnect to the same sandbox — this is the critical path that
+ // exercises CubeAPI's /sandboxes/{id}/connect endpoint.
+ reattached, err := client.Connect(ctx, sandboxID)
+ if err != nil {
+ t.Fatalf("Connect existing sandbox via real CubeAPI: %v", err)
+ }
+ if reattached == nil || reattached.ID() != sandboxID {
+ t.Fatalf("reattached sandbox ID = %s, want %s", reattached.ID(), sandboxID)
+ }
+
+ // Verify the reattached handle can also be looked up.
+ summary2, err := client.Get(ctx, sandboxID)
+ if err != nil {
+ t.Fatalf("Get after reconnect: %v", err)
+ }
+ if summary2 == nil || summary2.ID != sandboxID {
+ t.Fatalf("Get after reconnect returned unexpected summary: %#v", summary2)
+ }
+}
+
+// TestIntegrationCubeClient_LifecycleRoundTrip exercises the full lifecycle
+// against a real sandbox: Create → WriteFile → ReadFile → Exec → Delete.
+func TestIntegrationCubeClient_LifecycleRoundTrip(t *testing.T) {
+ cfg := integrationConfig(t)
+ client, err := NewCubeRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("NewCubeRemoteClient: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: cfg.CubeTemplate,
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: integrationSandboxTTL,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ sandboxID := handle.ID()
+ t.Logf("created sandbox %s", sandboxID)
+ t.Cleanup(func() {
+ cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := client.Delete(cleanupCtx, sandboxID); err != nil {
+ t.Logf("cleanup delete sandbox %s: %v", sandboxID, err)
+ }
+ })
+
+ // Write a file inside the sandbox.
+ path := "/tmp/weknora-integration.txt"
+ payload := []byte("hello from weknora integration\n")
+ if err := client.WriteFile(ctx, handle, path, payload); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+
+ // Read the file back.
+ got, err := client.ReadFile(ctx, handle, path)
+ if err != nil {
+ t.Fatalf("ReadFile: %v", err)
+ }
+ if !bytes.Equal(got, payload) {
+ t.Fatalf("read back mismatch: got=%q want=%q", string(got), string(payload))
+ }
+
+ // Run a shell command that echoes the file to stdout.
+ result, err := client.Exec(ctx, handle, RemoteExecRequest{
+ Command: "cat",
+ Args: []string{path},
+ WorkDir: "/tmp",
+ Timeout: integrationDefaultExecTimeout,
+ })
+ if err != nil {
+ t.Fatalf("Exec: %v", err)
+ }
+ if result.ExitCode != 0 {
+ t.Fatalf("Exec exit code: %d stderr=%q", result.ExitCode, result.Stderr)
+ }
+ if !strings.Contains(result.Stdout, "hello from weknora integration") {
+ t.Fatalf("stdout missing marker: %q", result.Stdout)
+ }
+
+ // Explicitly delete and verify it's gone.
+ if err := client.Delete(ctx, sandboxID); err != nil {
+ t.Fatalf("Delete: %v", err)
+ }
+ summary, err := client.Get(ctx, sandboxID)
+ if err != nil {
+ if IsRemoteNotFound(err) {
+ t.Logf("sandbox %s confirmed deleted (not-found)", sandboxID)
+ return
+ }
+ t.Fatalf("Get after delete: %v", err)
+ }
+ if summary != nil {
+ t.Logf("sandbox still visible right after delete (state=%s) — acceptable eventual-consistency window", summary.State)
+ }
+}
+
+// TestIntegrationCubeClient_FilesystemOps covers the filesystem RPCs:
+// MakeDir, WriteFile, ListDir, Stat, and Remove. It's kept separate from
+// the lifecycle test so failures point at the right subsystem.
+func TestIntegrationCubeClient_FilesystemOps(t *testing.T) {
+ cfg := integrationConfig(t)
+ client, err := NewCubeRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("NewCubeRemoteClient: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: cfg.CubeTemplate,
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: integrationSandboxTTL,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ _ = client.Delete(cleanupCtx, handle.ID())
+ })
+
+ base := "/tmp/weknora-fs"
+ if err := client.MakeDir(ctx, handle, base); err != nil {
+ t.Fatalf("MakeDir %s: %v", base, err)
+ }
+
+ // Write two files to verify listing.
+ src := base + "/one.txt"
+ another := base + "/another.txt"
+ if err := client.WriteFile(ctx, handle, src, []byte("aaa")); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+ if err := client.WriteFile(ctx, handle, another, []byte("bbb")); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+
+ entries, err := client.ListDir(ctx, handle, base)
+ if err != nil {
+ t.Fatalf("ListDir %s: %v", base, err)
+ }
+ foundOne := false
+ foundAnother := false
+ for _, e := range entries {
+ if e.Name == "one.txt" {
+ foundOne = true
+ }
+ if e.Name == "another.txt" {
+ foundAnother = true
+ }
+ }
+ if !foundOne || !foundAnother {
+ t.Fatalf("ListDir did not surface expected files: %#v", entries)
+ }
+
+ stat, err := client.Stat(ctx, handle, src)
+ if err != nil {
+ t.Fatalf("Stat %s: %v", src, err)
+ }
+ if stat == nil {
+ t.Fatalf("Stat returned nil for existing path %s", src)
+ }
+ if stat.Type != RemoteEntryFile {
+ t.Fatalf("Stat type=%q, want file", stat.Type)
+ }
+
+ missing, err := client.Stat(ctx, handle, base+"/does-not-exist")
+ if err != nil {
+ t.Fatalf("Stat missing: unexpected error %v", err)
+ }
+ if missing != nil {
+ t.Fatalf("Stat missing returned entry: %#v", missing)
+ }
+
+ if err := client.Remove(ctx, handle, src); err != nil {
+ t.Fatalf("Remove %s: %v", src, err)
+ }
+ remaining, err := client.ListDir(ctx, handle, base)
+ if err != nil {
+ t.Fatalf("ListDir after remove: %v", err)
+ }
+ for _, e := range remaining {
+ if e.Name == "one.txt" {
+ t.Fatalf("'one.txt' still present after Remove")
+ }
+ }
+
+ if err := client.Remove(ctx, handle, base); err != nil {
+ t.Fatalf("Remove %s: %v", base, err)
+ }
+}
+
+// -----------------------------------------------------------------------------
+// End-to-end tests through SessionBoundManager
+// -----------------------------------------------------------------------------
+
+// TestIntegrationRemoteSandbox_EphemeralExecute exercises the empty-SessionID
+// path through SessionBoundManager: the manager allocates a fresh MicroVM,
+// runs the script, and tears it down — same wire behaviour Docker/Local
+// sandboxes present per Execute.
+func TestIntegrationRemoteSandbox_EphemeralExecute(t *testing.T) {
+ mgr := newIntegrationManager(t)
+ script := writeIntegrationScript(t, "hello.py", "print('weknora-integration-hi')\n")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ result, err := mgr.Execute(ctx, &ExecuteConfig{
+ Script: script,
+ SkipValidation: true,
+ })
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ if result.ExitCode != 0 {
+ t.Fatalf("exit code %d stderr=%q err=%q", result.ExitCode, result.Stderr, result.Error)
+ }
+ if !strings.Contains(result.Stdout, "weknora-integration-hi") {
+ t.Fatalf("stdout missing expected marker: %q", result.Stdout)
+ }
+}
+
+// TestIntegrationSessionBoundManager_StatePersistsAcrossExecutes verifies
+// the flagship feature of the Cube backend: two Execute calls that share the
+// same SessionID must hit the same MicroVM, so packages installed / files
+// created by the first call are visible to the second.
+func TestIntegrationSessionBoundManager_StatePersistsAcrossExecutes(t *testing.T) {
+ mgr := newIntegrationManager(t)
+
+ baseCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+ ctx := integrationTenantContext(baseCtx)
+
+ first := writeIntegrationScript(t, "write.py", strings.Join([]string{
+ "with open('/tmp/weknora-session-marker', 'w') as f:",
+ " f.write('session-state-ok')",
+ "print('wrote marker')",
+ "",
+ }, "\n"))
+ second := writeIntegrationScript(t, "read.py", strings.Join([]string{
+ "with open('/tmp/weknora-session-marker') as f:",
+ " print('marker=' + f.read())",
+ "",
+ }, "\n"))
+
+ sess := "integration-sess-alpha"
+ if r, err := mgr.Execute(ctx, &ExecuteConfig{
+ Script: first, SessionID: sess, SkipValidation: true,
+ }); err != nil || r.ExitCode != 0 {
+ t.Fatalf("first Execute: err=%v exit=%d stderr=%q", err, safeExit(r), safeStderr(r))
+ }
+ r2, err := mgr.Execute(ctx, &ExecuteConfig{
+ Script: second, SessionID: sess, SkipValidation: true,
+ })
+ if err != nil {
+ t.Fatalf("second Execute: %v", err)
+ }
+ if r2.ExitCode != 0 {
+ t.Fatalf("second Execute exit=%d stderr=%q", r2.ExitCode, r2.Stderr)
+ }
+ if !strings.Contains(r2.Stdout, "marker=session-state-ok") {
+ t.Fatalf("session state didn't persist across executes; stdout=%q", r2.Stdout)
+ }
+
+ // Third leg: a *different* SessionID must NOT see the marker. This is
+ // the negative half of the isolation contract; skipping it would let a
+ // regression that collapses all sessions onto the same VM slip by.
+ miss := writeIntegrationScript(t, "miss.py", strings.Join([]string{
+ "import os",
+ "print('exists=' + str(os.path.exists('/tmp/weknora-session-marker')))",
+ "",
+ }, "\n"))
+ r3, err := mgr.Execute(ctx, &ExecuteConfig{
+ Script: miss, SessionID: "integration-sess-beta", SkipValidation: true,
+ })
+ if err != nil {
+ t.Fatalf("third Execute: %v", err)
+ }
+ if r3.ExitCode != 0 {
+ t.Fatalf("third Execute exit=%d stderr=%q", r3.ExitCode, r3.Stderr)
+ }
+ if !strings.Contains(r3.Stdout, "exists=False") {
+ t.Fatalf("session isolation broken; stdout=%q", r3.Stdout)
+ }
+}
+
+// TestIntegrationSessionBoundManager_DestroySession asserts that
+// DestroySession actually reaches CubeAPI and cleans the MicroVM up.
+func TestIntegrationSessionBoundManager_DestroySession(t *testing.T) {
+ mgr := newIntegrationManager(t)
+
+ baseCtx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ ctx := integrationTenantContext(baseCtx)
+
+ script := writeIntegrationScript(t, "touch.py", "print('destroy-me')\n")
+ if _, err := mgr.Execute(ctx, &ExecuteConfig{
+ Script: script,
+ SessionID: "integration-destroy",
+ SkipValidation: true,
+ }); err != nil {
+ t.Fatalf("prime Execute: %v", err)
+ }
+
+ if err := mgr.DestroySession(ctx, "integration-destroy"); err != nil {
+ t.Fatalf("DestroySession: %v", err)
+ }
+ // Second destroy is a no-op.
+ if err := mgr.DestroySession(ctx, "integration-destroy"); err != nil {
+ t.Fatalf("second DestroySession: %v", err)
+ }
+}
+
+// safeExit / safeStderr shield the assertion helpers above from nil results
+// so a transport error doesn't crash the test before we've had a chance to
+// report the real cause.
+func safeExit(r *ExecuteResult) int {
+ if r == nil {
+ return -1
+ }
+ return r.ExitCode
+}
+
+func safeStderr(r *ExecuteResult) string {
+ if r == nil {
+ return ""
+ }
+ return r.Stderr
+}
+
+// newIntegrationManager wires a SessionBoundManager against the live Cube
+// deployment described by integrationConfig. Every integration test uses this
+// helper so provider adapter, binding store, and existence checker stay in
+// one place.
+func newIntegrationManager(t *testing.T) *SessionBoundManager {
+ t.Helper()
+ cfg := integrationConfig(t)
+ client, err := NewCubeRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("NewCubeRemoteClient: %v", err)
+ }
+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
+ Config: cfg,
+ Client: client,
+ Store: NewMemorySessionSandboxBindingStore(),
+ Checker: PermissiveSessionExistenceChecker{},
+ })
+ if err != nil {
+ t.Fatalf("NewSessionBoundManager: %v", err)
+ }
+ t.Cleanup(func() { _ = mgr.Cleanup(context.Background()) })
+ return mgr
+}
+
+// integrationTenantContext supplies the tenant ID SessionBoundManager needs
+// when resolving session-scoped operations.
+func integrationTenantContext(parent context.Context) context.Context {
+ return context.WithValue(parent, types.TenantIDContextKey, uint64(1))
+}
diff --git a/internal/sandbox/cube_mock_test.go b/internal/sandbox/cube_mock_test.go
new file mode 100644
index 000000000..0abbe668c
--- /dev/null
+++ b/internal/sandbox/cube_mock_test.go
@@ -0,0 +1,461 @@
+package sandbox
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// cubeMockServer emulates the Cube control-plane API and envd data-plane
+// endpoints that the Cube SDK speaks to. CubeRemoteClient tests exercise the
+// adapter through its public surface without requiring a real Cube deployment.
+type cubeMockServer struct {
+ server *httptest.Server
+ mu sync.Mutex
+ createBody map[string]any
+ createCount atomic.Int32
+ killCount atomic.Int32
+ nextID atomic.Int64
+ sandboxes map[string]map[string]any // sandboxID → sandbox state record
+ executor func(sandboxID, cmd string, args []string) (stdout, stderr string, exitCode int)
+ files map[string]map[string][]byte // sandboxID → path → content
+ cmdHistory []commandRecord
+}
+
+type commandRecord struct {
+ sandboxID string
+ cmd string
+ args []string
+}
+
+func newCubeMockServer(t *testing.T) *cubeMockServer {
+ t.Helper()
+ m := &cubeMockServer{
+ sandboxes: map[string]map[string]any{},
+ files: map[string]map[string][]byte{},
+ }
+ m.server = httptest.NewServer(http.HandlerFunc(m.handle))
+ t.Cleanup(m.server.Close)
+ return m
+}
+
+func (m *cubeMockServer) URL() string { return m.server.URL }
+
+// SetExecutor installs a callback that is invoked when a command is executed
+// inside any sandbox managed by this mock.
+func (m *cubeMockServer) SetExecutor(f func(sandboxID, cmd string, args []string) (stdout, stderr string, exitCode int)) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.executor = f
+}
+
+func (m *cubeMockServer) handle(w http.ResponseWriter, r *http.Request) {
+ // envd data-plane requests are routed through the proxy with a Host
+ // header of the form "49983-{sandboxID}.{domain}". Detect and handle
+ // them before falling through to the control-plane routes.
+ if isEnvdRequest(r.Host, "cube.app") {
+ m.handleEnvd(w, r)
+ return
+ }
+
+ switch {
+ case r.URL.Path == "/sandboxes" && r.Method == http.MethodPost:
+ m.handleCreate(w, r)
+ case r.URL.Path == "/sandboxes" && r.Method == http.MethodGet:
+ m.handleList(w, r)
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") && strings.HasSuffix(r.URL.Path, "/connect") && r.Method == http.MethodPost:
+ m.handleConnect(w, r)
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodGet:
+ m.handleGetInfo(w, r)
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodDelete:
+ m.handleDelete(w, r)
+ case r.URL.Path == "/health" && r.Method == http.MethodGet:
+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
+ default:
+ http.NotFound(w, r)
+ }
+}
+
+func (m *cubeMockServer) handleCreate(w http.ResponseWriter, r *http.Request) {
+ m.createCount.Add(1)
+ body, _ := io.ReadAll(r.Body)
+ var raw map[string]any
+ _ = json.Unmarshal(body, &raw)
+ m.mu.Lock()
+ m.createBody = raw
+ id := "cube-" + strconv.FormatInt(m.nextID.Add(1), 10)
+ metadata := map[string]string{}
+ if rawMeta, ok := raw["metadata"].(map[string]any); ok {
+ for k, v := range rawMeta {
+ metadata[k] = fmt.Sprint(v)
+ }
+ }
+ m.sandboxes[id] = map[string]any{
+ "sandboxID": id,
+ "templateID": raw["templateID"],
+ "clientID": "client-" + id,
+ "state": "running",
+ "envdVersion": "test",
+ "metadata": metadata,
+ "startedAt": time.Now().UTC().Format(time.RFC3339),
+ }
+ m.files[id] = map[string][]byte{}
+ m.mu.Unlock()
+
+ writeJSON(w, http.StatusCreated, map[string]any{
+ "sandboxID": id,
+ "clientID": "client-" + id,
+ "envdVersion": "test",
+ "domain": "cube.app",
+ })
+}
+
+func (m *cubeMockServer) handleConnect(w http.ResponseWriter, r *http.Request) {
+ id := extractSandboxID(r.URL.Path, "/connect")
+ m.mu.Lock()
+ _, ok := m.sandboxes[id]
+ m.mu.Unlock()
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "sandboxID": id,
+ "clientID": "client-" + id,
+ "envdVersion": "test",
+ "domain": "cube.app",
+ })
+}
+
+func (m *cubeMockServer) handleGetInfo(w http.ResponseWriter, r *http.Request) {
+ id := extractSandboxID(r.URL.Path, "")
+ m.mu.Lock()
+ info, ok := m.sandboxes[id]
+ m.mu.Unlock()
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ writeJSON(w, http.StatusNotFound, map[string]string{"message": "sandbox not found"})
+ return
+ }
+ data := cloneMap(info)
+ data["sandboxID"] = id
+ writeJSON(w, http.StatusOK, data)
+}
+
+func (m *cubeMockServer) handleList(w http.ResponseWriter, r *http.Request) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ items := make([]map[string]any, 0, len(m.sandboxes))
+ for id, info := range m.sandboxes {
+ cp := cloneMap(info)
+ cp["sandboxID"] = id
+ items = append(items, cp)
+ }
+ writeJSON(w, http.StatusOK, items)
+}
+
+func (m *cubeMockServer) handleDelete(w http.ResponseWriter, r *http.Request) {
+ id := extractSandboxID(r.URL.Path, "")
+ m.mu.Lock()
+ _, ok := m.sandboxes[id]
+ if ok {
+ delete(m.sandboxes, id)
+ delete(m.files, id)
+ }
+ m.mu.Unlock()
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ m.killCount.Add(1)
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// handleEnvd intercepts data-plane requests that the Cube SDK sends through
+// the proxy. These carry a Host header like "49983-{sandboxID}.cube.app".
+func (m *cubeMockServer) handleEnvd(w http.ResponseWriter, r *http.Request) {
+ sandboxID := extractSandboxIDFromHost(r.Host, "cube.app")
+ if sandboxID == "" {
+ http.NotFound(w, r)
+ return
+ }
+
+ switch {
+ case strings.Contains(r.URL.Path, "/process.Process/Start"):
+ body, _ := io.ReadAll(r.Body)
+ r.Body = io.NopCloser(bytes.NewBuffer(body))
+ m.handleCommandExec(w, r, sandboxID)
+ case strings.Contains(r.URL.Path, "/filesystem") && (strings.Contains(r.URL.Path, "Read") || strings.Contains(r.URL.Path, "Stat") || strings.Contains(r.URL.Path, "ListDir")):
+ m.handleFileRead(w, r, sandboxID)
+ case strings.Contains(r.URL.Path, "/filesystem") && strings.Contains(r.URL.Path, "MakeDir"):
+ body, _ := io.ReadAll(r.Body)
+ r.Body = io.NopCloser(bytes.NewBuffer(body))
+ writeJSON(w, http.StatusOK, map[string]any{"type": "directory"})
+ case strings.Contains(r.URL.Path, "/files") || containsPath(r.URL.Path, "Write"):
+ body, _ := io.ReadAll(r.Body)
+ r.Body = io.NopCloser(bytes.NewBuffer(body))
+ m.handleFileWrite(w, r, sandboxID)
+ default:
+ writeJSON(w, http.StatusOK, map[string]any{})
+ }
+}
+
+// handleCommandExec intercepts envd /process.Process/Start and dispatches to
+// the mock's executor callback.
+func (m *cubeMockServer) handleCommandExec(w http.ResponseWriter, r *http.Request, sandboxID string) {
+ m.mu.Lock()
+ exec := m.executor
+ m.mu.Unlock()
+ if exec == nil {
+ writeEnvdCommandResult(w, "", "", 0)
+ return
+ }
+
+ cmd := "/bin/bash"
+ args := []string{"-l", "-c", "<shell-line>"}
+ body, _ := io.ReadAll(r.Body)
+ // The envd body is connect-framed: [1 byte flags][4 bytes big-endian len][JSON].
+ if len(body) >= 5 {
+ msgLen := binary.BigEndian.Uint32(body[1:5])
+ if int(msgLen)+5 <= len(body) {
+ jsonBytes := body[5 : 5+int(msgLen)]
+ var req struct {
+ Process struct {
+ Cmd string `json:"cmd"`
+ Args []string `json:"args"`
+ } `json:"process"`
+ }
+ if json.Unmarshal(jsonBytes, &req) == nil && req.Process.Cmd != "" {
+ cmd = req.Process.Cmd
+ args = req.Process.Args
+ }
+ }
+ }
+
+ m.mu.Lock()
+ m.cmdHistory = append(m.cmdHistory, commandRecord{
+ sandboxID: sandboxID,
+ cmd: cmd,
+ args: args,
+ })
+ m.mu.Unlock()
+
+ stdout, stderr, code := exec(sandboxID, cmd, args)
+ writeEnvdCommandResult(w, stdout, stderr, code)
+}
+
+func (m *cubeMockServer) handleFileWrite(w http.ResponseWriter, r *http.Request, sandboxID string) {
+ body, _ := io.ReadAll(r.Body)
+ r.Body = io.NopCloser(bytes.NewBuffer(body))
+
+ // The Cube SDK sends WriteFile as POST /files?path=%2Fworkspace%2Fhello.txt
+ // with the raw file content as the body (no connect framing).
+ path := r.URL.Query().Get("path")
+ if path == "" || !strings.HasPrefix(path, "/") {
+ path = "/workspace/unknown"
+ }
+
+ m.mu.Lock()
+ if m.files[sandboxID] == nil {
+ m.files[sandboxID] = map[string][]byte{}
+ }
+ // Store only the raw file content, not the full HTTP body framing.
+ m.files[sandboxID][path] = body
+ m.mu.Unlock()
+
+ writeJSON(w, http.StatusOK, map[string]any{})
+}
+
+// extractFilePathFromBody strips connect framing from the body and parses
+// the JSON content to extract the file path. The Cube SDK uses connect+json
+// for filesystem RPC, so the body is: [1 byte flags][4 bytes big-endian len][JSON].
+// The JSON contains a "path" field.
+func extractFilePathFromBody(body []byte) string {
+ // Strip connect frame envelope: 1 byte flags + 4 bytes big-endian length.
+ if len(body) < 5 {
+ return "/workspace/unknown"
+ }
+ msgLen := binary.BigEndian.Uint32(body[1:5])
+ if int(msgLen)+5 > len(body) {
+ return "/workspace/unknown"
+ }
+ jsonBytes := body[5 : 5+int(msgLen)]
+
+ var req struct {
+ Path string `json:"path"`
+ }
+ if json.Unmarshal(jsonBytes, &req) == nil && strings.HasPrefix(req.Path, "/") {
+ return req.Path
+ }
+ return "/workspace/unknown"
+}
+
+func (m *cubeMockServer) handleFileRead(w http.ResponseWriter, _ *http.Request, sandboxID string) {
+ m.mu.Lock()
+ files := m.files[sandboxID]
+ m.mu.Unlock()
+ if files == nil {
+ writeJSON(w, http.StatusOK, map[string]any{"content": ""})
+ return
+ }
+ // Return the content of the requested file.
+ writeJSON(w, http.StatusOK, map[string]any{"content": ""})
+}
+
+// --- helpers ---
+
+func cloneMap(src map[string]any) map[string]any {
+ dst := make(map[string]any, len(src))
+ for k, v := range src {
+ dst[k] = v
+ }
+ return dst
+}
+
+func writeJSON(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func writeEnvdCommandResult(w http.ResponseWriter, stdout, stderr string, exitCode int) {
+ // The Cube SDK ProcessEvent format: {"event":{...}}
+ // stdout/stderr in data events MUST be base64-encoded (SDK calls
+ // base64.StdEncoding.DecodeString on them).
+ // Stream must include: start event, optional data events, end event,
+ // then an end-of-stream connect frame (flags=0x02).
+ var body bytes.Buffer
+
+ // start event
+ startJSON, _ := json.Marshal(map[string]any{
+ "event": map[string]any{
+ "start": map[string]any{"pid": 1},
+ },
+ })
+ writeConnectFrame(&body, startJSON)
+
+ // data event (if there is output) — stdout/stderr must be base64-encoded
+ if stdout != "" || stderr != "" {
+ dataJSON, _ := json.Marshal(map[string]any{
+ "event": map[string]any{
+ "data": map[string]any{
+ "stdout": base64Encode(stdout),
+ "stderr": base64Encode(stderr),
+ },
+ },
+ })
+ writeConnectFrame(&body, dataJSON)
+ }
+
+ // end event
+ endJSON, _ := json.Marshal(map[string]any{
+ "event": map[string]any{
+ "end": map[string]any{
+ "exitCode": exitCode,
+ "exited": true,
+ },
+ },
+ })
+ writeConnectFrame(&body, endJSON)
+
+ // End-of-stream frame (connectEndStreamFlag = 0x02, empty payload).
+ var eosHeader [5]byte
+ eosHeader[0] = 0x02 // end-stream flag
+ body.Write(eosHeader[:])
+
+ w.Header().Set("Content-Type", "application/connect+json")
+ w.Header().Set("Trailer", "grpc-status")
+ w.Header().Set("Trailer", "grpc-message")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(body.Bytes())
+ w.Header().Set("grpc-status", "0")
+ w.Header().Set("grpc-message", "")
+}
+
+// base64Encode returns base64-encoded string, or empty string for empty input.
+func base64Encode(s string) string {
+ if s == "" {
+ return ""
+ }
+ return base64.StdEncoding.EncodeToString([]byte(s))
+}
+
+// writeConnectFrame appends a connect-framed message to buf:
+// [1 byte flags=0x00][4 bytes big-endian length][payload]
+func writeConnectFrame(buf *bytes.Buffer, payload []byte) {
+ var header [5]byte
+ binary.BigEndian.PutUint32(header[1:5], uint32(len(payload)))
+ buf.Write(header[:])
+ buf.Write(payload)
+}
+
+func extractSandboxID(urlPath string, suffix string) string {
+ path := urlPath
+ if suffix != "" {
+ path = strings.TrimSuffix(path, suffix)
+ }
+ parts := strings.Split(strings.Trim(path, "/"), "/")
+ if len(parts) >= 2 && parts[0] == "sandboxes" {
+ return parts[1]
+ }
+ return ""
+}
+
+func extractSandboxIDFromHost(host string, domain string) string {
+ // Strip port if present (Go HTTP request Host may include port).
+ if h, _, err := net.SplitHostPort(host); err == nil {
+ host = h
+ }
+ // Host format is "{port}-{sandboxID}.{domain}". Strip the port
+ // prefix (everything before the first "-").
+ idx := strings.Index(host, "-")
+ if idx < 0 {
+ return ""
+ }
+ host = host[idx+1:]
+ // Strip the domain suffix.
+ host = strings.TrimSuffix(host, "."+domain)
+ return host
+}
+
+func isEnvdRequest(host, domain string) bool {
+ if h, _, err := net.SplitHostPort(host); err == nil {
+ host = h
+ }
+ return strings.Contains(host, "-") && strings.HasSuffix(host, "."+domain)
+}
+
+func containsPath(urlPath, needle string) bool {
+ return strings.Contains(urlPath, needle)
+}
+
+// testConfig builds a *Config wired against the mock server. Both the control
+// plane (CubeAPIURL) and the data plane (CubeProxyURL) are pointed at the
+// mock so every SDK-initiated request goes through the mock's net/http server.
+func testConfig(t *testing.T, mock *cubeMockServer) *Config {
+ t.Helper()
+ return &Config{
+ Type: SandboxTypeCube,
+ CubeAPIURL: mock.URL(),
+ CubeAPIKey: "",
+ CubeProxyURL: mock.URL(),
+ CubeTemplate: "template-a",
+ CubeSandboxDomain: "cube.app",
+ CubeSandboxTTL: 30 * time.Minute,
+ CubeHTTPTimeout: 30 * time.Second,
+ DefaultTimeout: 60 * time.Second,
+ }
+}
diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.go
new file mode 100644
index 000000000..ae86bc89b
--- /dev/null
+++ b/internal/sandbox/cube_remote_client.go
@@ -0,0 +1,785 @@
+// Package sandbox: Cube adapter for the provider-neutral RemoteSandboxClient.
+//
+// CubeRemoteClient implements RemoteSandboxClient on top of the Cube SDK and
+// envd transport. Callers speak RemoteSandboxClient; Cube-specific types,
+// HTTP status codes, and workarounds never leak past this file — every return
+// value is either a neutral DTO or a RemoteError with a stable Kind.
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"
+)
+
+// CubeRemoteClient implements RemoteSandboxClient on top of the Cube SDK and
+// envd transport. It is the only Cube backend the manager and lifecycle
+// coordinator see.
+type CubeRemoteClient struct {
+ config *Config
+ client *cubesandbox.Client
+ sandboxDomain string
+ httpTimeout time.Duration
+}
+
+// NewCubeRemoteClient constructs a Cube-backed RemoteSandboxClient using the
+// SDK default HTTP clients (separate control/data pools). Suitable for the
+// process-wide default manager and for throwaway connectivity probes, neither
+// of which benefits from an externally owned pool.
+func NewCubeRemoteClient(config *Config) (*CubeRemoteClient, error) {
+ return NewCubeRemoteClientWithPool(config, nil)
+}
+
+// NewCubeRemoteClientWithPool builds a client whose connections come from a
+// caller-owned pool. Named configs construct a client per request, so the pool
+// is what keeps connections alive across requests; it routes control-plane
+// traffic onto the transport shared with E2B while preserving the SDK's
+// proxy dial rewrite for the data plane. A nil pool keeps the SDK defaults.
+func NewCubeRemoteClientWithPool(
+ config *Config,
+ pool *CubeTransportPool,
+) (*CubeRemoteClient, error) {
+ if config == nil {
+ return nil, errors.New("cube remote client config is required")
+ }
+ httpTimeout := config.CubeHTTPTimeout
+ if httpTimeout <= 0 {
+ httpTimeout = DefaultCubeHTTPTimeout
+ }
+ sdkCfg := cubesandbox.Config{
+ APIURL: config.CubeAPIURL,
+ APIKey: config.CubeAPIKey,
+ TemplateID: config.CubeTemplate,
+ SandboxDomain: config.CubeSandboxDomain,
+ Timeout: config.CubeHTTPTimeout,
+ RequestTimeout: config.CubeHTTPTimeout,
+ }
+
+ if proxyHost, proxyPort, proxyScheme, ok := parseProxyURL(config.CubeProxyURL); ok {
+ sdkCfg.ProxyNodeIP = proxyHost
+ sdkCfg.ProxyPortHTTP = proxyPort
+ sdkCfg.ProxyScheme = proxyScheme
+ }
+
+ var opts []cubesandbox.ClientOption
+ if pool != nil {
+ httpClient := &http.Client{
+ Timeout: httpTimeout,
+ Transport: pool.RoundTripperFor(config),
+ }
+ opts = append(opts, cubesandbox.WithHTTPClient(httpClient))
+ }
+
+ return &CubeRemoteClient{
+ config: config,
+ client: cubesandbox.NewClient(
+ sdkCfg,
+ opts...,
+ ),
+ sandboxDomain: config.CubeSandboxDomain,
+ httpTimeout: httpTimeout,
+ }, nil
+}
+
+// cubeRemoteHandle is the RemoteSandboxHandle Cube returns. It wraps the SDK's
+// *cubesandbox.Sandbox directly; all envd calls (WriteFile / RunCommand / …)
+// dispatch through sb. Metadata is cached at creation time so Metadata()
+// can return it without a network round-trip.
+type cubeRemoteHandle struct {
+ sb *cubesandbox.Sandbox
+ metadata map[string]string
+}
+
+func (h *cubeRemoteHandle) ID() string {
+ if h == nil || h.sb == nil {
+ return ""
+ }
+ return h.sb.SandboxID
+}
+
+func (h *cubeRemoteHandle) Provider() RemoteProvider { return SandboxTypeCube }
+
+func (h *cubeRemoteHandle) Metadata() map[string]string {
+ if h == nil {
+ return nil
+ }
+ return cloneMetadata(h.metadata)
+}
+
+// --- RemoteSandboxClient ------------------------------------------------------
+
+func (c *CubeRemoteClient) Provider() RemoteProvider { return SandboxTypeCube }
+
+func (c *CubeRemoteClient) Capabilities() RemoteSandboxCapabilities {
+ return RemoteSandboxCapabilities{
+ SupportsReconnect: true,
+ SupportsMetadata: true,
+ SupportsListSandboxes: true,
+ SupportsPauseResume: true,
+ SupportsTimeoutRefresh: true,
+ SupportsFilesystemEnumeration: true,
+ // Cube's CreateOptions has no volume-mount field yet; revisit when the
+ // official Go SDK reaches v0.6.0.
+ SupportsVolumes: false,
+ }
+}
+
+func (c *CubeRemoteClient) Health(ctx context.Context) error {
+ if _, err := c.client.Health(ctx); err != nil {
+ logger.Errorf(ctx, "cube remote client health check failed: %v", err)
+ return normalizeCubeError("Health", err)
+ }
+ return nil
+}
+
+func (c *CubeRemoteClient) Create(
+ ctx context.Context,
+ request RemoteCreateRequest,
+) (RemoteSandboxHandle, error) {
+ if strings.TrimSpace(request.TemplateID) == "" {
+ return nil, cubeInvalidRequest("Create", "template ID is required", nil)
+ }
+ timeout, err := cubeTimeout(request.Timeout)
+ if err != nil {
+ return nil, cubeInvalidRequest("Create", err.Error(), err)
+ }
+ action := request.Timeout.Action
+ autoResume := request.Timeout.AutoResume
+ if action == "" {
+ action = RemoteOnTimeoutKill
+ }
+ if action != RemoteOnTimeoutKill && action != RemoteOnTimeoutPause {
+ return nil, cubeInvalidRequest(
+ "Create",
+ fmt.Sprintf("unsupported timeout action %q", action),
+ nil,
+ )
+ }
+ if request.Timeout.AutoResume && action != RemoteOnTimeoutPause {
+ return nil, cubeInvalidRequest(
+ "Create",
+ "auto resume requires pause on timeout",
+ nil,
+ )
+ }
+ // Cube honours two independent switches for outbound reachability and
+ // both must be on for "curl https://example.com" to work from inside
+ // the VM:
+ //
+ // * AllowInternetAccess (top-level, cluster egress switch): when
+ // nil the SDK omits the field and the server falls back to the
+ // template's default. Setting it explicitly makes the intent
+ // obvious to anyone reading a captured payload and keeps
+ // behaviour identical when the template default flips.
+ // * Network.AllowPublicTraffic (per-sandbox routing switch): tells
+ // CubeProxy to attach the public-egress interface to this MicroVM.
+ // Without it the VM has no outbound route regardless of the
+ // cluster-level allow.
+ //
+ // Callers can override either switch via cubeCreateRequest.Network.
+ // The permissive (both on) defaults preserve the pre-refactor
+ // behaviour for callers that leave the policy unset.
+ //
+ // See docs/guide/network-policy.md ("示例 7: 混合 L3 allow 和 L7 rules").
+ network := request.Network
+ if network.AllowInternetAccess == nil {
+ defaultOn := true
+ network.AllowInternetAccess = &defaultOn
+ }
+ if network.AllowPublicTraffic == nil {
+ defaultOn := true
+ network.AllowPublicTraffic = &defaultOn
+ }
+ opts := cubesandbox.CreateOptions{
+ TemplateID: request.TemplateID,
+ Timeout: timeout,
+ EnvVars: cloneMetadata(request.EnvVars),
+ Metadata: cloneMetadata(request.Metadata),
+ AllowInternetAccess: network.AllowInternetAccess,
+ Network: cubesandbox.NetworkOptions{
+ AllowPublicTraffic: network.AllowPublicTraffic,
+ AllowOut: append([]string(nil), network.AllowOut...),
+ DenyOut: append([]string(nil), network.DenyOut...),
+ },
+ }
+ if action != "" {
+ opts.Extra = map[string]any{
+ "lifecycle": map[string]any{
+ "onTimeout": string(action),
+ "autoResume": autoResume,
+ },
+ }
+ }
+ sb, err := c.client.Create(ctx, opts)
+ if err != nil {
+ return nil, normalizeCubeError("Create", err)
+ }
+ if sb == nil || sb.SandboxID == "" {
+ return nil, errors.New("cube api: create sandbox: empty sandboxID")
+ }
+ return &cubeRemoteHandle{
+ sb: sb,
+ metadata: cloneMetadata(request.Metadata),
+ }, nil
+}
+
+func (c *CubeRemoteClient) Connect(
+ ctx context.Context,
+ sandboxID string,
+) (RemoteSandboxHandle, error) {
+ if strings.TrimSpace(sandboxID) == "" {
+ return nil, cubeInvalidRequest("Connect", "sandbox ID is required", nil)
+ }
+ sb, err := c.client.Connect(ctx, sandboxID)
+ if err != nil {
+ return nil, normalizeCubeError("Connect", err)
+ }
+ if sb == nil || sb.SandboxID == "" {
+ return nil, NewRemoteError(
+ SandboxTypeCube, "Connect", RemoteErrorKindInternal,
+ "cube returned an empty sandbox handle", nil,
+ )
+ }
+ return &cubeRemoteHandle{sb: sb}, nil
+}
+
+func (c *CubeRemoteClient) Get(
+ ctx context.Context,
+ sandboxID string,
+) (*RemoteSandboxSummary, error) {
+ if strings.TrimSpace(sandboxID) == "" {
+ return nil, cubeInvalidRequest("Get", "sandbox ID is required", nil)
+ }
+ sb, err := c.client.Connect(ctx, sandboxID)
+ if err != nil {
+ return nil, normalizeCubeError("Get", err)
+ }
+ info, err := sb.GetInfo(ctx)
+ if err != nil {
+ if isSDKNotFound(err) {
+ return nil, NewRemoteError(
+ SandboxTypeCube, "Get", RemoteErrorKindNotFound,
+ "sandbox not found", nil,
+ )
+ }
+ return nil, normalizeCubeError("Get", err)
+ }
+ if info == nil {
+ return nil, NewRemoteError(
+ SandboxTypeCube, "Get", RemoteErrorKindNotFound,
+ "sandbox not found", nil,
+ )
+ }
+ return cubeRemoteSummary(*info), nil
+}
+
+func (c *CubeRemoteClient) List(
+ ctx context.Context,
+ filter RemoteListFilter,
+) ([]RemoteSandboxSummary, error) {
+ sandboxInfos, err := c.client.List(ctx)
+ if err != nil {
+ return nil, normalizeCubeError("List", err)
+ }
+ result := make([]RemoteSandboxSummary, 0, len(sandboxInfos))
+ for _, summary := range sandboxInfos {
+ converted := cubeRemoteSummary(summary)
+ if !metadataMatches(converted.Metadata, filter.Metadata) ||
+ !StateMatches(converted.State, filter.States) {
+ continue
+ }
+ result = append(result, *converted)
+ }
+ return result, nil
+}
+
+func (c *CubeRemoteClient) Delete(ctx context.Context, sandboxID string) error {
+ if strings.TrimSpace(sandboxID) == "" {
+ return cubeInvalidRequest("Delete", "sandbox ID is required", nil)
+ }
+ sb, err := c.client.Connect(ctx, sandboxID)
+ if err != nil {
+ return normalizeCubeError("Delete", err)
+ }
+ if err := sb.Kill(ctx); err != nil {
+ return normalizeCubeError("Delete", err)
+ }
+ return nil
+}
+
+func (c *CubeRemoteClient) Exec(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ request RemoteExecRequest,
+) (*RemoteExecResult, error) {
+ sb, err := cubeHandleSandbox("Exec", handle)
+ if err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(request.Command) == "" {
+ return nil, cubeInvalidRequest("Exec", "command is required", nil)
+ }
+ if request.Shell && len(request.Args) != 0 {
+ return nil, cubeInvalidRequest(
+ "Exec", "shell execution cannot include argv arguments", nil,
+ )
+ }
+ if request.Timeout < 0 {
+ return nil, cubeInvalidRequest("Exec", "execution timeout cannot be negative", nil)
+ }
+
+ execCtx := ctx
+ cancel := func() {}
+ if request.Timeout > 0 {
+ execCtx, cancel = context.WithTimeout(ctx, request.Timeout)
+ }
+ defer cancel()
+
+ line := request.Command
+ if !request.Shell {
+ line = buildShellLine(request.Command, request.Args)
+ }
+ if request.Stdin != "" {
+ line = wrapWithStdin(line, request.Stdin)
+ }
+ envs := cloneMetadata(request.Env)
+ if envs == nil {
+ envs = map[string]string{}
+ }
+
+ startedAt := time.Now()
+ // User comes from the neutral request rather than being hardcoded: running
+ // everything as root silently defeats file-mode protections on shared
+ // volumes, and made this adapter behave differently from E2B's.
+ sdkResult, execErr := sb.Commands().Run(execCtx, line, cubesandbox.CommandOptions{
+ Timeout: request.Timeout,
+ Envs: envs,
+ Cwd: request.WorkDir,
+ User: request.User,
+ })
+ duration := time.Since(startedAt)
+
+ if execErr != nil {
+ if request.Timeout > 0 &&
+ errors.Is(execCtx.Err(), context.DeadlineExceeded) {
+ return &RemoteExecResult{
+ Duration: duration,
+ Killed: true,
+ ExitCode: -1,
+ }, nil
+ }
+ return nil, normalizeCubeError("Exec", execErr)
+ }
+ if sdkResult == nil {
+ return nil, NewRemoteError(
+ SandboxTypeCube, "Exec", RemoteErrorKindInternal,
+ "cube returned an empty command result", nil,
+ )
+ }
+ return &RemoteExecResult{
+ Stdout: sdkResult.Stdout,
+ Stderr: sdkResult.Stderr,
+ ExitCode: sdkResult.ExitCode,
+ Duration: duration,
+ }, nil
+}
+
+func (c *CubeRemoteClient) WriteFile(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+ content []byte,
+) error {
+ sb, err := cubeHandleSandbox("WriteFile", handle)
+ if err != nil {
+ return err
+ }
+ if err := sb.Files().Write(ctx, path, content); err != nil {
+ return normalizeCubeError("WriteFile", err)
+ }
+ return nil
+}
+
+func (c *CubeRemoteClient) ReadFile(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) ([]byte, error) {
+ sb, err := cubeHandleSandbox("ReadFile", handle)
+ if err != nil {
+ return nil, err
+ }
+ content, err := sb.Files().Read(ctx, path)
+ if err != nil {
+ return nil, normalizeCubeError("ReadFile", err)
+ }
+ return []byte(content), nil
+}
+
+func (c *CubeRemoteClient) ListDir(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) ([]RemoteDirEntry, error) {
+ sb, err := cubeHandleSandbox("ListDir", handle)
+ if err != nil {
+ return nil, err
+ }
+ if path == "" {
+ path = "/"
+ }
+ entries, err := sb.Files().List(ctx, path)
+ if err != nil {
+ return nil, normalizeCubeError("ListDir", err)
+ }
+ result := make([]RemoteDirEntry, 0, len(entries))
+ for _, e := range entries {
+ result = append(result, RemoteDirEntry{
+ Name: e.Name,
+ Path: e.Path,
+ Type: cubeRemoteEntryType(normaliseFileType(e.Type)),
+ Size: e.Size,
+ ModTime: cubeModTime(e.ModifiedTime),
+ })
+ }
+ return result, nil
+}
+
+// normaliseFileType maps envd's proto enum strings ("FILE_TYPE_FILE",
+// "FILE_TYPE_DIRECTORY", …) onto the short lowercase names WeKnora already
+// stores.
+func normaliseFileType(t string) string {
+ switch strings.ToUpper(t) {
+ case "FILE_TYPE_FILE", "FILE":
+ return "file"
+ case "FILE_TYPE_DIRECTORY", "DIRECTORY":
+ return "directory"
+ case "FILE_TYPE_SYMLINK", "SYMLINK":
+ return "symlink"
+ default:
+ if t == "" {
+ return ""
+ }
+ return strings.ToLower(t)
+ }
+}
+
+func (c *CubeRemoteClient) MakeDir(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) error {
+ sb, err := cubeHandleSandbox("MakeDir", handle)
+ if err != nil {
+ return err
+ }
+ if _, err := sb.Files().MakeDir(ctx, path); err != nil {
+ return normalizeCubeError("MakeDir", err)
+ }
+ return nil
+}
+
+func (c *CubeRemoteClient) Remove(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) error {
+ sb, err := cubeHandleSandbox("Remove", handle)
+ if err != nil {
+ return err
+ }
+ if err := sb.Files().Remove(ctx, path); err != nil {
+ return normalizeCubeError("Remove", err)
+ }
+ return nil
+}
+
+func (c *CubeRemoteClient) Stat(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) (*RemoteStatEntry, error) {
+ sb, err := cubeHandleSandbox("Stat", handle)
+ if err != nil {
+ return nil, err
+ }
+ entry, err := sb.Files().Stat(ctx, path)
+ if err != nil {
+ if isSDKNotFound(err) {
+ return nil, NewRemoteError(
+ SandboxTypeCube, "Stat", RemoteErrorKindNotFound,
+ "path not found", nil,
+ )
+ }
+ return nil, normalizeCubeError("Stat", err)
+ }
+ if entry == nil {
+ return nil, NewRemoteError(
+ SandboxTypeCube, "Stat", RemoteErrorKindNotFound,
+ "path not found", nil,
+ )
+ }
+ return &RemoteStatEntry{
+ Path: entry.Path,
+ Type: cubeRemoteEntryType(normaliseFileType(entry.Type)),
+ Size: entry.Size,
+ ModTime: cubeModTime(entry.ModifiedTime),
+ }, nil
+}
+
+// --- helpers -----------------------------------------------------------------
+
+// isSDKNotFound spots the SDK's "resource missing" errors without having to
+// import its internal error types. Both explicit NotFoundError values and
+// textual "not found" mentions in wrapped errors are recognised.
+func isSDKNotFound(err error) bool {
+ if err == nil {
+ return false
+ }
+ var nfe *cubesandbox.NotFoundError
+ if errors.As(err, &nfe) {
+ return true
+ }
+ lower := strings.ToLower(err.Error())
+ return strings.Contains(lower, "not found") ||
+ strings.Contains(lower, "no such file") ||
+ strings.Contains(lower, "sandbox_not_found") ||
+ strings.Contains(lower, "http 404")
+}
+
+func cubeTimeout(policy RemoteTimeoutPolicy) (*time.Duration, error) {
+ switch policy.Mode {
+ case "", RemoteTimeoutServerDefault:
+ return nil, nil
+ case RemoteTimeoutExplicit:
+ value := policy.Value
+ if value < 0 {
+ value = cubesandbox.NeverTimeout
+ }
+ return &value, nil
+ default:
+ return nil, fmt.Errorf("unsupported timeout mode %q", policy.Mode)
+ }
+}
+
+// cubeHandleSandbox extracts the SDK *cubesandbox.Sandbox from an opaque
+// RemoteSandboxHandle. Returns an error when the handle is nil, not Cube,
+// or has an empty sandbox ID.
+func cubeHandleSandbox(op string, handle RemoteSandboxHandle) (*cubesandbox.Sandbox, error) {
+ cubeHandle, ok := handle.(*cubeRemoteHandle)
+ if !ok || cubeHandle == nil || cubeHandle.sb == nil ||
+ strings.TrimSpace(cubeHandle.sb.SandboxID) == "" {
+ return nil, cubeInvalidRequest(op, "handle was not issued by Cube", nil)
+ }
+ return cubeHandle.sb, nil
+}
+
+// cubeRemoteSummary converts the SDK's SandboxInfo (from List / GetInfo) into
+// the provider-neutral RemoteSandboxSummary DTO.
+func cubeRemoteSummary(info cubesandbox.SandboxInfo) *RemoteSandboxSummary {
+ out := &RemoteSandboxSummary{
+ ID: info.SandboxID,
+ TemplateID: info.TemplateID,
+ State: normalizeCubeState(info.State),
+ RawState: info.State,
+ Metadata: cloneMetadata(info.Metadata),
+ StartedAt: info.StartedAt,
+ }
+ if info.EndAt != nil {
+ out.EndAt = *info.EndAt
+ }
+ return out
+}
+
+// parseProxyURL turns "http://127.0.0.1:80" into ("127.0.0.1", 80, "http").
+// A missing port defaults to 80/443 depending on the scheme; an unparseable
+// URL returns ok=false so callers can fall back to the SDK's defaults.
+func parseProxyURL(raw string) (host string, port int, scheme string, ok bool) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return "", 0, "", false
+ }
+ parsed, err := url.Parse(raw)
+ if err != nil || parsed.Host == "" {
+ return "", 0, "", false
+ }
+ scheme = strings.ToLower(parsed.Scheme)
+ if scheme == "" {
+ scheme = "http"
+ }
+ h, p, err := net.SplitHostPort(parsed.Host)
+ if err != nil {
+ h = parsed.Host
+ if scheme == "https" {
+ p = "443"
+ } else {
+ p = "80"
+ }
+ }
+ portInt, err := strconv.Atoi(p)
+ if err != nil || portInt <= 0 {
+ return "", 0, "", false
+ }
+ return h, portInt, scheme, true
+}
+
+// buildShellLine turns argv into a single shell-safe command line. It matches
+// the semantics of the old hand-rolled path, which relied on envd's bash to
+// resolve `python3` (or similar) against $PATH inside the sandbox image.
+func buildShellLine(cmd string, args []string) string {
+ parts := make([]string, 0, len(args)+1)
+ parts = append(parts, shellQuote(cmd))
+ for _, a := range args {
+ parts = append(parts, shellQuote(a))
+ }
+ return strings.Join(parts, " ")
+}
+
+// wrapWithStdin funnels a caller-supplied stdin payload into the child
+// process by prepending a heredoc. This keeps the SDK's Commands.Run contract
+// (which does not take an explicit stdin argument) usable in the rare case
+// callers actually need to pipe data.
+func wrapWithStdin(line, stdin string) string {
+ // Use a heredoc delimiter unlikely to appear in caller data.
+ const delim = "WEKNORA_STDIN_EOF"
+ // Escape lines containing the delimiter defensively.
+ safe := strings.ReplaceAll(stdin, delim, "")
+ return "cat <<'" + delim + "' | " + line + "\n" + safe + "\n" + delim
+}
+
+// shellQuote wraps s in single quotes, escaping any embedded quotes. Suitable
+// for building a /bin/bash -c line where every argv element should be treated
+// as literal text.
+func shellQuote(s string) string {
+ if s == "" {
+ return "''"
+ }
+ // Only bare tokens (alnum, dash, underscore, slash, dot, comma, colon,
+ // equals, plus) can be passed unquoted; everything else gets single
+ // quotes.
+ if isShellSafe(s) {
+ return s
+ }
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+func isShellSafe(s string) bool {
+ for _, r := range s {
+ switch {
+ case r >= 'a' && r <= 'z':
+ case r >= 'A' && r <= 'Z':
+ case r >= '0' && r <= '9':
+ case r == '-' || r == '_' || r == '/' || r == '.' || r == ',' ||
+ r == ':' || r == '=' || r == '+':
+ default:
+ return false
+ }
+ }
+ return true
+}
+func normalizeCubeState(state string) RemoteSandboxState {
+ switch strings.ToLower(strings.TrimSpace(state)) {
+ case "running", "available":
+ return RemoteStateRunning
+ case "paused":
+ return RemoteStatePaused
+ case "pending", "creating", "provisioning", "starting", "pausing", "resuming":
+ return RemoteStateTransitioning
+ case "killing", "killed", "terminated", "stopped", "deleted", "failed", "error":
+ return RemoteStateTerminal
+ default:
+ return RemoteStateUnknown
+ }
+}
+
+func cubeRemoteEntryType(entryType string) RemoteDirEntryType {
+ switch strings.ToLower(strings.TrimSpace(entryType)) {
+ case "file":
+ return RemoteEntryFile
+ case "directory", "dir":
+ return RemoteEntryDir
+ default:
+ return RemoteEntryOther
+ }
+}
+
+func cubeModTime(value string) time.Time {
+ for _, layout := range []string{time.RFC3339Nano, time.RFC3339} {
+ parsed, err := time.Parse(layout, value)
+ if err == nil {
+ return parsed
+ }
+ }
+ return time.Time{}
+}
+
+func StateMatches(candidate RemoteSandboxState, allowed []RemoteSandboxState) bool {
+ if len(allowed) == 0 {
+ return true
+ }
+ for _, state := range allowed {
+ if candidate == state {
+ return true
+ }
+ }
+ return false
+}
+
+func cubeInvalidRequest(op, message string, cause error) error {
+ return NewRemoteError(
+ SandboxTypeCube, op, RemoteErrorKindInvalidRequest, message, cause,
+ )
+}
+
+// normalizeCubeError projects a Cube-native error (SDK sentinel, APIError,
+// net.Error, context cancellation) onto a RemoteError with a stable Kind. The
+// original error is preserved via errors.Unwrap for diagnostics.
+func normalizeCubeError(op string, err error) error {
+ if err == nil {
+ return nil
+ }
+ if errors.Is(err, context.Canceled) {
+ return fmt.Errorf("cube %s: %w", op, err)
+ }
+
+ kind := RemoteErrorKindInternal
+ switch {
+ case errors.Is(err, context.DeadlineExceeded):
+ kind = RemoteErrorKindTimeout
+ case errors.Is(err, cubesandbox.ErrAuthentication):
+ kind = RemoteErrorKindAuthentication
+ case errors.Is(err, cubesandbox.ErrTemplateNotFound):
+ kind = RemoteErrorKindInvalidRequest
+ case errors.Is(err, cubesandbox.ErrSandboxNotFound):
+ kind = RemoteErrorKindNotFound
+ default:
+ var pathNotFound *cubesandbox.NotFoundError
+ var apiErr *cubesandbox.APIError
+ var netErr net.Error
+ switch {
+ case errors.As(err, &pathNotFound):
+ kind = RemoteErrorKindNotFound
+ case errors.As(err, &apiErr):
+ kind = httpErrorKind(op, apiErr.StatusCode)
+ case errors.As(err, &netErr) && netErr.Timeout():
+ kind = RemoteErrorKindTimeout
+ case errors.As(err, &netErr):
+ kind = RemoteErrorKindUnavailable
+ }
+ }
+ return NewRemoteError(SandboxTypeCube, op, kind, err.Error(), err)
+}
+
+var (
+ _ RemoteSandboxClient = (*CubeRemoteClient)(nil)
+ _ RemoteSandboxHandle = (*cubeRemoteHandle)(nil)
+)
diff --git a/internal/sandbox/cube_remote_client_test.go b/internal/sandbox/cube_remote_client_test.go
new file mode 100644
index 000000000..b9737b3df
--- /dev/null
+++ b/internal/sandbox/cube_remote_client_test.go
@@ -0,0 +1,394 @@
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "testing"
+ "time"
+
+ cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"
+
+ "github.com/stretchr/testify/require"
+)
+
+// newTestCubeRemoteClient wires a real CubeRemoteClient at the cubeMockServer.
+// Tests exercise the adapter through its public RemoteSandboxClient surface
+// only — no intermediate backend interfaces exist below CubeRemoteClient.
+func newTestCubeRemoteClient(t *testing.T, mock *cubeMockServer) *CubeRemoteClient {
+ t.Helper()
+ client, err := NewCubeRemoteClient(testConfig(t, mock))
+ require.NoError(t, err)
+ return client
+}
+
+func TestCubeRemoteClientProviderAndCapabilities(t *testing.T) {
+ client := newTestCubeRemoteClient(t, newCubeMockServer(t))
+
+ require.Equal(t, SandboxTypeCube, client.Provider())
+ require.Equal(t, RemoteSandboxCapabilities{
+ SupportsReconnect: true,
+ SupportsMetadata: true,
+ SupportsListSandboxes: true,
+ SupportsPauseResume: true,
+ SupportsTimeoutRefresh: true,
+ SupportsFilesystemEnumeration: true,
+ }, client.Capabilities())
+}
+
+func TestCubeRemoteClientCreateWritesLifecyclePayload(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+
+ handle, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: 15 * time.Minute,
+ Action: RemoteOnTimeoutPause,
+ AutoResume: true,
+ },
+ Metadata: map[string]string{"owner": "session-a"},
+ EnvVars: map[string]string{"LANG": "C.UTF-8"},
+ })
+ require.NoError(t, err)
+ require.NotEmpty(t, handle.ID())
+ require.Equal(t, SandboxTypeCube, handle.Provider())
+ require.Equal(t, map[string]string{"owner": "session-a"}, handle.Metadata())
+
+ mock.mu.Lock()
+ body := mock.createBody
+ mock.mu.Unlock()
+ require.Equal(t, "template-a", body["templateID"])
+ require.Equal(t, float64(900), body["timeout"])
+ require.Equal(t, map[string]any{"owner": "session-a"}, body["metadata"])
+ require.Equal(t, map[string]any{"LANG": "C.UTF-8"}, body["envVars"])
+ require.Equal(t, map[string]any{
+ "onTimeout": "pause",
+ "autoResume": true,
+ }, body["lifecycle"])
+}
+
+func TestCubeRemoteClientCreateForwardsNetworkPolicy(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client, err := NewCubeRemoteClient(testConfig(t, mock))
+ require.NoError(t, err)
+ deny := false
+ privateSandbox := false
+
+ _, err = client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Network: RemoteNetworkPolicy{
+ AllowInternetAccess: &deny,
+ AllowPublicTraffic: &privateSandbox,
+ AllowOut: []string{"*.example.com"},
+ DenyOut: []string{"0.0.0.0/0"},
+ },
+ })
+ require.NoError(t, err)
+
+ mock.mu.Lock()
+ body := mock.createBody
+ mock.mu.Unlock()
+ require.Equal(t, false, body["allowInternetAccess"])
+ networkPayload, ok := body["network"].(map[string]any)
+ require.True(t, ok, "network payload missing: %#v", body["network"])
+ require.Equal(t, false, networkPayload["allowPublicTraffic"])
+ require.Equal(t, []any{"*.example.com"}, networkPayload["allowOut"])
+ require.Equal(t, []any{"0.0.0.0/0"}, networkPayload["denyOut"])
+}
+
+func TestCubeRemoteClientCreatePreservesTimeoutModes(t *testing.T) {
+ t.Run("server default omits timeout", func(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutServerDefault,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ require.NoError(t, err)
+ mock.mu.Lock()
+ body := mock.createBody
+ mock.mu.Unlock()
+ _, hasTimeout := body["timeout"]
+ require.False(t, hasTimeout)
+ })
+
+ t.Run("negative means never", func(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: -time.Hour,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ require.NoError(t, err)
+ mock.mu.Lock()
+ body := mock.createBody
+ mock.mu.Unlock()
+ // Cube's three-value semantics send -1 verbatim as "never timeout".
+ require.Equal(t, float64(-1), body["timeout"])
+ })
+
+ t.Run("auto resume requires pause", func(t *testing.T) {
+ client := newTestCubeRemoteClient(t, newCubeMockServer(t))
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: time.Minute,
+ Action: RemoteOnTimeoutKill,
+ AutoResume: true,
+ },
+ })
+ require.True(t, IsRemoteInvalidRequest(err))
+ })
+
+ t.Run("missing template rejected before wire", func(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ _, err := client.Create(context.Background(), RemoteCreateRequest{})
+ require.True(t, IsRemoteInvalidRequest(err))
+ require.Zero(t, mock.createCount.Load())
+ })
+}
+
+func TestCubeRemoteClientLifecycleRoundTrip(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ ctx := context.Background()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: time.Minute,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ require.NoError(t, err)
+
+ summary, err := client.Get(ctx, handle.ID())
+ require.NoError(t, err)
+ require.Equal(t, handle.ID(), summary.ID)
+ require.Equal(t, RemoteStateRunning, summary.State)
+
+ list, err := client.List(ctx, RemoteListFilter{
+ States: []RemoteSandboxState{RemoteStateRunning},
+ })
+ require.NoError(t, err)
+ require.Len(t, list, 1)
+ require.Equal(t, handle.ID(), list[0].ID)
+
+ reconnected, err := client.Connect(ctx, handle.ID())
+ require.NoError(t, err)
+ require.Equal(t, handle.ID(), reconnected.ID())
+
+ require.NoError(t, client.Delete(ctx, handle.ID()))
+ require.Equal(t, int32(1), mock.killCount.Load())
+ mock.mu.Lock()
+ _, stillAlive := mock.sandboxes[handle.ID()]
+ mock.mu.Unlock()
+ require.False(t, stillAlive)
+}
+
+func TestCubeRemoteClientExecArgvAndShell(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ ctx := context.Background()
+
+ var (
+ gotCmd string
+ gotArgs []string
+ )
+ mock.SetExecutor(func(_, cmd string, args []string) (string, string, int) {
+ gotCmd = cmd
+ gotArgs = args
+ return "ok\n", "", 0
+ })
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutServerDefault,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ require.NoError(t, err)
+
+ // Argv → cubeClient assembles /bin/bash -l -c "<shell-quoted argv>". The
+ // mock records the wrapper argv, which lets us assert both the wrapper
+ // shape and that the caller's arguments are shell-quoted (not lost).
+ result, err := client.Exec(ctx, handle, RemoteExecRequest{
+ Command: "python3",
+ Args: []string{"script.py", "argument with spaces"},
+ })
+ require.NoError(t, err)
+ require.Equal(t, 0, result.ExitCode)
+ require.Contains(t, result.Stdout, "ok")
+ require.Equal(t, "/bin/bash", gotCmd)
+ require.Len(t, gotArgs, 3)
+ require.Equal(t, "-l", gotArgs[0])
+ require.Equal(t, "-c", gotArgs[1])
+ require.Contains(t, gotArgs[2], "python3")
+ require.Contains(t, gotArgs[2], "'argument with spaces'")
+
+ // Shell → the caller's raw expression is passed through verbatim.
+ gotCmd, gotArgs = "", nil
+ mock.SetExecutor(func(_, cmd string, args []string) (string, string, int) {
+ gotCmd = cmd
+ gotArgs = args
+ return "shell\n", "", 0
+ })
+ _, err = client.Exec(ctx, handle, RemoteExecRequest{
+ Command: "printf '%s' ok | cat",
+ Shell: true,
+ })
+ require.NoError(t, err)
+ require.Equal(t, "/bin/bash", gotCmd)
+ require.Equal(t, "printf '%s' ok | cat", gotArgs[2])
+
+ // Shell + argv is mutually exclusive.
+ _, err = client.Exec(ctx, handle, RemoteExecRequest{
+ Command: "echo",
+ Args: []string{"unsafe ambiguity"},
+ Shell: true,
+ })
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestCubeRemoteClientExecTimeoutIsKilled(t *testing.T) {
+ mock := newCubeMockServer(t)
+ // A slow executor lets the outer request timeout fire before the mock
+ // returns a stream. cubeClient's RunCommand cancellation path then
+ // synthesises Killed=true, ExitCode=-1.
+ mock.SetExecutor(func(string, string, []string) (string, string, int) {
+ time.Sleep(200 * time.Millisecond)
+ return "", "", 0
+ })
+ client := newTestCubeRemoteClient(t, mock)
+ ctx := context.Background()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ })
+ require.NoError(t, err)
+
+ result, err := client.Exec(ctx, handle, RemoteExecRequest{
+ Command: "sleep",
+ Args: []string{"10"},
+ Timeout: 20 * time.Millisecond,
+ })
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.True(t, result.Killed)
+ require.Equal(t, -1, result.ExitCode)
+}
+
+func TestCubeRemoteClientFileWriteRoundTrip(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ ctx := context.Background()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+
+ require.NoError(t, client.WriteFile(ctx, handle, "/workspace/hello.txt", []byte("hi")))
+ require.NoError(t, client.MakeDir(ctx, handle, "/workspace/nested"))
+
+ mock.mu.Lock()
+ files := mock.files[handle.ID()]
+ mock.mu.Unlock()
+ require.Equal(t, "hi", string(files["/workspace/hello.txt"]))
+}
+
+func TestCubeRemoteClientRejectsForeignHandle(t *testing.T) {
+ client := newTestCubeRemoteClient(t, newCubeMockServer(t))
+ _, err := client.ReadFile(
+ context.Background(),
+ &contractHandle{id: "e2b-1", provider: SandboxTypeE2B},
+ "/workspace/file",
+ )
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestCubeRemoteClientListFilters(t *testing.T) {
+ mock := newCubeMockServer(t)
+ client := newTestCubeRemoteClient(t, mock)
+ ctx := context.Background()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "keep"},
+ })
+ require.NoError(t, err)
+ _, err = client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "other"},
+ })
+ require.NoError(t, err)
+
+ list, err := client.List(ctx, RemoteListFilter{
+ Metadata: map[string]string{"owner": "keep"},
+ })
+ require.NoError(t, err)
+ require.Len(t, list, 1)
+ require.Equal(t, handle.ID(), list[0].ID)
+}
+
+func TestNormalizeCubeState(t *testing.T) {
+ tests := map[string]RemoteSandboxState{
+ "running": RemoteStateRunning,
+ "paused": RemoteStatePaused,
+ "pausing": RemoteStateTransitioning,
+ "resuming": RemoteStateTransitioning,
+ "pending": RemoteStateTransitioning,
+ "killing": RemoteStateTerminal,
+ "killed": RemoteStateTerminal,
+ "terminated": RemoteStateTerminal,
+ "deleted": RemoteStateTerminal,
+ "failed": RemoteStateTerminal,
+ "": RemoteStateUnknown,
+ "weird": RemoteStateUnknown,
+ }
+ for raw, want := range tests {
+ require.Equalf(t, want, normalizeCubeState(raw), "state %q", raw)
+ }
+}
+
+func TestNormalizeCubeError(t *testing.T) {
+ tests := []struct {
+ name string
+ op string
+ err error
+ kind RemoteErrorKind
+ }{
+ {"sandbox not found", "Get", cubesandbox.ErrSandboxNotFound, RemoteErrorKindNotFound},
+ {"template not found", "Create", cubesandbox.ErrTemplateNotFound, RemoteErrorKindInvalidRequest},
+ {"authentication", "Health", cubesandbox.ErrAuthentication, RemoteErrorKindAuthentication},
+ {"path not found", "Stat", &cubesandbox.NotFoundError{Path: "/x"}, RemoteErrorKindNotFound},
+ {"gone", "Get", &cubesandbox.APIError{StatusCode: http.StatusGone}, RemoteErrorKindTerminal},
+ {"conflict", "Connect", &cubesandbox.APIError{StatusCode: http.StatusConflict}, RemoteErrorKindConflict},
+ {"rate limited", "Create", &cubesandbox.APIError{StatusCode: http.StatusTooManyRequests}, RemoteErrorKindCapacity},
+ {"bad gateway", "List", &cubesandbox.APIError{StatusCode: http.StatusBadGateway}, RemoteErrorKindUnavailable},
+ {"deadline", "Exec", context.DeadlineExceeded, RemoteErrorKindTimeout},
+ {"unknown", "List", errors.New("unknown"), RemoteErrorKindInternal},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := normalizeCubeError(tt.op, tt.err)
+ var remoteErr *RemoteError
+ require.ErrorAs(t, err, &remoteErr)
+ require.Equal(t, tt.kind, remoteErr.Kind)
+ require.Equal(t, SandboxTypeCube, remoteErr.Provider)
+ require.ErrorIs(t, err, tt.err)
+ })
+ }
+}
diff --git a/internal/sandbox/cube_transport.go b/internal/sandbox/cube_transport.go
new file mode 100644
index 000000000..d8ce45055
--- /dev/null
+++ b/internal/sandbox/cube_transport.go
@@ -0,0 +1,131 @@
+// Package sandbox: connection pooling for per-request Cube clients.
+//
+// Named Cube configs build a fresh client on every Resolve, so without an
+// externally owned transport every request would open new TCP connections to
+// both the CubeAPI control plane and the envd proxy.
+//
+// Cube cannot reuse the single shared transport E2B uses, because the SDK
+// speaks two planes with different dialling rules:
+//
+// - control plane (Create/Connect/List) talks to CubeAPIURL directly;
+// - data plane (exec, filesystem) addresses sandboxes as
+// "49983-{id}.{domain}" but must dial CubeProxyURL, keeping the sandbox
+// authority in the Host header so the proxy can route it.
+//
+// Handing the SDK one http.Client for both planes (WithHTTPClient overwrites
+// controlHTTP and dataHTTP alike) drops that dial rewrite, which only appears
+// to work when DNS happens to resolve the sandbox domain to the proxy node on
+// the same port. This file keeps the rewrite by routing per request: control
+// traffic rides the process-wide transport shared with E2B, data traffic rides
+// a transport cached per proxy endpoint so configs pointing at the same proxy
+// share one pool.
+package sandbox
+
+import (
+ "context"
+ "net"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// CubeTransportPool owns the transports handed to per-request Cube clients.
+// One instance lives for the process; clients built from it come and go.
+type CubeTransportPool struct {
+ control http.RoundTripper
+
+ // data maps a proxy "host:port" to the transport that dials it.
+ data sync.Map
+}
+
+// NewCubeTransportPool returns a pool whose control plane rides control.
+// A nil control transport installs a guarded one.
+func NewCubeTransportPool(control http.RoundTripper) *CubeTransportPool {
+ if control == nil {
+ control = NewGuardedTransport()
+ }
+ return &CubeTransportPool{control: control}
+}
+
+// RoundTripperFor returns the transport a client built from cfg should use.
+// Configs without a usable proxy URL keep every request on the control
+// transport, matching the SDK's behaviour when no proxy node is configured.
+func (p *CubeTransportPool) RoundTripperFor(cfg *Config) http.RoundTripper {
+ split := &cubeSplitTransport{
+ control: p.control,
+ sandboxDomain: strings.ToLower(strings.TrimSpace(cfg.CubeSandboxDomain)),
+ }
+ if host, port, _, ok := parseProxyURL(cfg.CubeProxyURL); ok {
+ split.data = p.dataTransport(net.JoinHostPort(host, strconv.Itoa(port)))
+ }
+ return split
+}
+
+// dataTransport returns the transport dialling target, creating it once.
+func (p *CubeTransportPool) dataTransport(target string) http.RoundTripper {
+ if existing, ok := p.data.Load(target); ok {
+ return existing.(http.RoundTripper)
+ }
+ actual, _ := p.data.LoadOrStore(target, newCubeDataTransport(target))
+ return actual.(http.RoundTripper)
+}
+
+// newCubeDataTransport dials target regardless of the request's authority,
+// mirroring the SDK's proxy rewrite while adding the outbound address guard
+// the SDK has no notion of.
+func newCubeDataTransport(target string) *http.Transport {
+ dialer := &net.Dialer{
+ Timeout: 10 * time.Second,
+ KeepAlive: 30 * time.Second,
+ Control: SafeDialControl,
+ }
+ return &http.Transport{
+ // The proxy is addressed directly; an ambient HTTP proxy would
+ // defeat the rewrite.
+ Proxy: nil,
+ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return dialer.DialContext(ctx, network, target)
+ },
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 4,
+ IdleConnTimeout: 90 * time.Second,
+ }
+}
+
+// cubeSplitTransport routes a request to the control or the data transport by
+// looking at the authority the SDK addressed.
+type cubeSplitTransport struct {
+ control http.RoundTripper
+ data http.RoundTripper
+ sandboxDomain string
+}
+
+func (t *cubeSplitTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ if t.data != nil && t.isDataPlane(req.URL.Hostname()) {
+ return t.data.RoundTrip(req)
+ }
+ return t.control.RoundTrip(req)
+}
+
+// isDataPlane reports whether host addresses a sandbox rather than CubeAPI.
+// Anything else - including an unset sandbox domain - stays on the control
+// transport, so a misconfiguration cannot silently redirect API calls at the
+// proxy.
+func (t *cubeSplitTransport) isDataPlane(host string) bool {
+ if t.sandboxDomain == "" {
+ return false
+ }
+ host = strings.ToLower(host)
+ return host == t.sandboxDomain || strings.HasSuffix(host, "."+t.sandboxDomain)
+}
+
+// CloseIdleConnections keeps the SDK's post-rollback reset meaningful. Only
+// the data pool is dropped: the control transport is shared with every other
+// tenant and with E2B, and one sandbox's restart is no reason to close it.
+func (t *cubeSplitTransport) CloseIdleConnections() {
+ if closer, ok := t.data.(interface{ CloseIdleConnections() }); ok {
+ closer.CloseIdleConnections()
+ }
+}
diff --git a/internal/sandbox/cube_transport_test.go b/internal/sandbox/cube_transport_test.go
new file mode 100644
index 000000000..0fd453be7
--- /dev/null
+++ b/internal/sandbox/cube_transport_test.go
@@ -0,0 +1,137 @@
+package sandbox
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+// countingRoundTripper records how many requests rode the control transport.
+type countingRoundTripper struct {
+ next http.RoundTripper
+ mu sync.Mutex
+ hosts []string
+}
+
+func (c *countingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
+ c.mu.Lock()
+ c.hosts = append(c.hosts, req.URL.Host)
+ c.mu.Unlock()
+ return c.next.RoundTrip(req)
+}
+
+func (c *countingRoundTripper) seen() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]string(nil), c.hosts...)
+}
+
+// The data plane addresses sandboxes as "49983-{id}.{domain}" but must dial
+// the configured proxy. Sharing one transport across both planes drops that
+// rewrite, which is exactly the regression this guards: the proxy has to see
+// the request, and it has to see the sandbox authority in the Host header.
+func TestCubeTransportPoolRoutesDataPlaneThroughProxy(t *testing.T) {
+ t.Setenv(AllowPrivateEndpointsEnv, "true")
+
+ api := newCubeMockServer(t)
+
+ var mu sync.Mutex
+ var proxyHosts []string
+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ proxyHosts = append(proxyHosts, r.Host)
+ mu.Unlock()
+ api.handle(w, r)
+ }))
+ t.Cleanup(proxy.Close)
+
+ cfg := testConfig(t, api)
+ cfg.CubeProxyURL = proxy.URL
+
+ control := &countingRoundTripper{next: NewGuardedTransport()}
+ client, err := NewCubeRemoteClientWithPool(cfg, NewCubeTransportPool(control))
+ require.NoError(t, err)
+
+ ctx := context.Background()
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: time.Minute,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ require.NoError(t, err)
+
+ api.SetExecutor(func(string, string, []string) (string, string, int) {
+ return "ok", "", 0
+ })
+ result, err := client.Exec(ctx, handle, RemoteExecRequest{Command: "echo", Args: []string{"ok"}})
+ require.NoError(t, err)
+ require.Equal(t, 0, result.ExitCode)
+
+ mu.Lock()
+ gotProxyHosts := append([]string(nil), proxyHosts...)
+ mu.Unlock()
+ require.NotEmpty(t, gotProxyHosts, "data plane never reached the proxy")
+ require.Contains(t, gotProxyHosts[0], "49983-"+handle.ID()+".cube.app")
+
+ // Control-plane calls ride the shared transport; data-plane calls do not.
+ for _, host := range control.seen() {
+ require.NotContains(t, host, "cube.app")
+ }
+ require.NotEmpty(t, control.seen())
+}
+
+// Configs pointing at the same proxy must share one pool - otherwise building
+// a client per request pools nothing.
+func TestCubeTransportPoolReusesTransportPerProxyEndpoint(t *testing.T) {
+ pool := NewCubeTransportPool(NewGuardedTransport())
+
+ first := pool.RoundTripperFor(&Config{
+ CubeProxyURL: "http://127.0.0.1:8080",
+ CubeSandboxDomain: "cube.app",
+ }).(*cubeSplitTransport)
+ second := pool.RoundTripperFor(&Config{
+ CubeProxyURL: "http://127.0.0.1:8080",
+ CubeSandboxDomain: "cube.app",
+ }).(*cubeSplitTransport)
+ other := pool.RoundTripperFor(&Config{
+ CubeProxyURL: "http://127.0.0.1:9090",
+ CubeSandboxDomain: "cube.app",
+ }).(*cubeSplitTransport)
+
+ require.Same(t, first.data, second.data)
+ require.NotSame(t, first.data, other.data)
+ require.Same(t, first.control, other.control)
+}
+
+// Without a usable proxy URL the SDK dials the sandbox authority directly, so
+// the split transport must not invent a data plane.
+func TestCubeTransportPoolWithoutProxyKeepsEverythingOnControl(t *testing.T) {
+ pool := NewCubeTransportPool(NewGuardedTransport())
+
+ split := pool.RoundTripperFor(&Config{CubeSandboxDomain: "cube.app"}).(*cubeSplitTransport)
+
+ // A nil data transport is what sends sandbox authorities back to control.
+ require.Nil(t, split.data)
+}
+
+func TestCubeSplitTransportClassifiesAuthorities(t *testing.T) {
+ split := &cubeSplitTransport{
+ control: NewGuardedTransport(),
+ data: NewGuardedTransport(),
+ sandboxDomain: "cube.app",
+ }
+
+ require.True(t, split.isDataPlane("49983-abc.cube.app"))
+ require.True(t, split.isDataPlane("49983-ABC.Cube.App"))
+ require.False(t, split.isDataPlane("api.example.com"))
+ // A lookalike suffix must not be mistaken for the sandbox domain.
+ require.False(t, split.isDataPlane("evilcube.app"))
+}
diff --git a/internal/sandbox/defaults.go b/internal/sandbox/defaults.go
new file mode 100644
index 000000000..6c3696bc9
--- /dev/null
+++ b/internal/sandbox/defaults.go
@@ -0,0 +1,189 @@
+// Package sandbox: configuration defaults and deployment baseline.
+//
+// DeploymentConfig reads WEKNORA_SANDBOX_* into the process-wide baseline. That
+// baseline backs agents which selected no named config; it is NOT merged into
+// named configs, so the built-in endpoint constants below stay on this path only
+// (see tenant_config.go for why).
+//
+// The provider defaults come in two flavours. Deployment defaults fill endpoints
+// and templates and exist so a developer can run `WEKNORA_SANDBOX_MODE=cube` with
+// an empty .env. Runtime defaults fill TTLs and HTTP timeouts and are safe
+// anywhere, because those have meaningful built-in values while an endpoint does
+// not.
+package sandbox
+
+import (
+ "os"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// DeploymentConfig returns the process-wide *Config built from WEKNORA_SANDBOX_*.
+func DeploymentConfig() *Config {
+ mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
+ switch mode {
+ case "cube":
+ return cubeConfigFromEnv()
+ case "e2b":
+ return e2bConfigFromEnv()
+ case "docker":
+ cfg := DefaultConfig()
+ cfg.Type = SandboxTypeDocker
+ if v := os.Getenv("WEKNORA_SANDBOX_DOCKER_IMAGE"); v != "" {
+ cfg.DockerImage = v
+ }
+ return cfg
+ case "local":
+ cfg := DefaultConfig()
+ cfg.Type = SandboxTypeLocal
+ return cfg
+ default:
+ cfg := DefaultConfig()
+ cfg.Type = SandboxTypeDisabled
+ return cfg
+ }
+}
+
+// CubeConfigFromEnv assembles a Cube *Config from WEKNORA_SANDBOX_CUBE_* env vars.
+func CubeConfigFromEnv() *Config {
+ return cubeConfigFromEnv()
+}
+
+// E2BConfigFromEnv assembles an E2B *Config from WEKNORA_SANDBOX_E2B_* env vars.
+func E2BConfigFromEnv() *Config {
+ return e2bConfigFromEnv()
+}
+
+func cubeConfigFromEnv() *Config {
+ cfg := DefaultConfig()
+ cfg.Type = SandboxTypeCube
+ cfg.FallbackEnabled = false
+
+ if v := os.Getenv("WEKNORA_SANDBOX_CUBE_API_URL"); v != "" {
+ cfg.CubeAPIURL = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_CUBE_PROXY_URL"); v != "" {
+ cfg.CubeProxyURL = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN"); v != "" {
+ cfg.CubeSandboxDomain = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_CUBE_API_KEY"); v != "" {
+ cfg.CubeAPIKey = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_CUBE_TEMPLATE"); v != "" {
+ cfg.CubeTemplate = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_CUBE_SANDBOX_TTL"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ cfg.CubeSandboxTTL = time.Duration(n) * time.Second
+ }
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ cfg.CubeHTTPTimeout = time.Duration(n) * time.Second
+ }
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ cfg.DefaultTimeout = time.Duration(n) * time.Second
+ }
+ }
+ // After the environment so an explicit value always wins.
+ applyCubeDeploymentDefaults(cfg)
+ applyCubeRuntimeDefaults(cfg)
+ return cfg
+}
+
+func e2bConfigFromEnv() *Config {
+ cfg := DefaultConfig()
+ cfg.Type = SandboxTypeE2B
+ cfg.FallbackEnabled = false
+
+ if v := os.Getenv("WEKNORA_SANDBOX_E2B_API_KEY"); v != "" {
+ cfg.E2BAPIKey = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_E2B_API_URL"); v != "" {
+ cfg.E2BAPIURL = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN"); v != "" {
+ cfg.E2BSandboxDomain = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_E2B_TEMPLATE"); v != "" {
+ cfg.E2BTemplate = v
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_E2B_SANDBOX_TTL"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ cfg.E2BSandboxTTL = time.Duration(n) * time.Second
+ }
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ cfg.E2BHTTPTimeout = time.Duration(n) * time.Second
+ }
+ }
+ if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ cfg.DefaultTimeout = time.Duration(n) * time.Second
+ }
+ }
+ applyE2BRuntimeDefaults(cfg)
+ return cfg
+}
+
+// applyCubeDeploymentDefaults fills the Cube endpoint, domain and template with
+// the built-in single-node values so `WEKNORA_SANDBOX_MODE=cube` works out of the
+// box on a developer machine.
+//
+// It is reachable from the deployment baseline only. Named configs must not see
+// these constants: inheriting them is how a workspace config ends up dialling
+// 127.0.0.1 instead of being told which field it forgot.
+func applyCubeDeploymentDefaults(cfg *Config) {
+ if cfg == nil {
+ return
+ }
+ if cfg.CubeAPIURL == "" {
+ cfg.CubeAPIURL = DefaultCubeAPIURL
+ }
+ if cfg.CubeProxyURL == "" {
+ cfg.CubeProxyURL = DefaultCubeProxyURL
+ }
+ if cfg.CubeSandboxDomain == "" {
+ cfg.CubeSandboxDomain = DefaultCubeSandboxDomain
+ }
+ if cfg.CubeTemplate == "" {
+ cfg.CubeTemplate = DefaultCubeTemplate
+ }
+}
+
+// applyCubeRuntimeDefaults fills the Cube tuning fields downstream code relies
+// on being non-zero. Unlike the endpoint defaults these are safe everywhere:
+// a TTL or an HTTP timeout has a sane built-in value, an endpoint does not.
+// Safe to call multiple times.
+func applyCubeRuntimeDefaults(cfg *Config) {
+ if cfg == nil {
+ return
+ }
+ if cfg.CubeSandboxTTL <= 0 {
+ cfg.CubeSandboxTTL = DefaultCubeSandboxTTL
+ }
+ if cfg.CubeHTTPTimeout <= 0 {
+ cfg.CubeHTTPTimeout = DefaultCubeHTTPTimeout
+ }
+}
+
+// applyE2BRuntimeDefaults is applyCubeRuntimeDefaults for E2B. There is no
+// applyE2BDeploymentDefaults: go-e2b resolves its own API base URL and sandbox
+// domain, and it ships no template ID that would work for anyone.
+func applyE2BRuntimeDefaults(cfg *Config) {
+ if cfg == nil {
+ return
+ }
+ if cfg.E2BSandboxTTL <= 0 {
+ cfg.E2BSandboxTTL = DefaultE2BSandboxTTL
+ }
+ if cfg.E2BHTTPTimeout <= 0 {
+ cfg.E2BHTTPTimeout = DefaultE2BHTTPTimeout
+ }
+}
diff --git a/internal/sandbox/e2b_integration_test.go b/internal/sandbox/e2b_integration_test.go
new file mode 100644
index 000000000..2880ca4d3
--- /dev/null
+++ b/internal/sandbox/e2b_integration_test.go
@@ -0,0 +1,339 @@
+//go:build e2b_integration
+
+// E2B integration tests use a dedicated build tag so they can run independently
+// of the legacy Cube integration suite, which currently has a separate
+// newCubeClient compile blocker in this workspace.
+//
+// Run with:
+//
+// go test -tags=e2b_integration ./internal/sandbox \
+// -run '^TestE2BIntegration' -count=1 -v -timeout=15m
+
+package sandbox
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+const (
+ e2bIntegrationTTL = 30 * time.Second
+ e2bIntegrationHTTPTimeout = 30 * time.Second
+ e2bIntegrationPauseTimeout = 3 * time.Minute
+ e2bIntegrationPollInterval = 5 * time.Second
+)
+
+func TestE2BIntegrationLifecycleParity(t *testing.T) {
+ cfg := e2bIntegrationConfig(t)
+ store := NewMemorySessionSandboxBindingStore()
+ key := SessionSandboxKey{
+ TenantID: 1,
+ SessionID: fmt.Sprintf("e2b-integration-%d", time.Now().UnixNano()),
+ }
+ createRequest := RemoteCreateRequest{
+ TemplateID: cfg.E2BTemplate,
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: e2bIntegrationTTL,
+ Action: RemoteOnTimeoutPause,
+ AutoResume: true,
+ },
+ }
+
+ firstClient := newE2BIntegrationClient(t, cfg)
+ firstLifecycle := newE2BIntegrationLifecycle(t, firstClient, store, createRequest)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
+ defer cancel()
+
+ var sandboxID string
+ destroyed := false
+ t.Cleanup(func() {
+ if sandboxID == "" || destroyed {
+ return
+ }
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cleanupCancel()
+ if err := firstClient.Delete(cleanupCtx, sandboxID); err != nil {
+ if CanReplaceRemoteBinding(err) {
+ t.Logf("best-effort cleanup found E2B sandbox %s already absent", sandboxID)
+ return
+ }
+ t.Errorf("best-effort cleanup failed for E2B sandbox %s", sandboxID)
+ return
+ }
+ t.Logf("best-effort cleanup deleted E2B sandbox %s", sandboxID)
+ })
+
+ firstHandle, err := firstLifecycle.Resolve(ctx, key)
+ if err != nil {
+ t.Fatalf("initial lifecycle Resolve: %v", err)
+ }
+ sandboxID = firstHandle.ID()
+ if sandboxID == "" {
+ t.Fatal("initial lifecycle Resolve returned an empty sandbox ID")
+ }
+
+ expectedMetadata := firstLifecycle.metadata(key)
+ if !metadataMatches(firstHandle.Metadata(), expectedMetadata) {
+ t.Fatalf("lifecycle-created sandbox handle omitted ownership metadata: got=%v want=%v",
+ firstHandle.Metadata(), expectedMetadata)
+ }
+
+ base := "/tmp/weknora-e2b-integration"
+ path := base + "/state.txt"
+ payload := []byte("e2b lifecycle state persists\n")
+ if err := firstClient.MakeDir(ctx, firstHandle, base); err != nil {
+ t.Fatalf("MakeDir: %v", err)
+ }
+ if err := firstClient.WriteFile(ctx, firstHandle, path, payload); err != nil {
+ t.Fatalf("WriteFile: %v", err)
+ }
+ entries, err := firstClient.ListDir(ctx, firstHandle, base)
+ if err != nil {
+ t.Fatalf("ListDir: %v", err)
+ }
+ found := false
+ for _, entry := range entries {
+ if entry.Name == "state.txt" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("ListDir did not return state.txt: %#v", entries)
+ }
+ stat, err := firstClient.Stat(ctx, firstHandle, path)
+ if err != nil {
+ t.Fatalf("Stat: %v", err)
+ }
+ if stat == nil || stat.Type != RemoteEntryFile || stat.Size != int64(len(payload)) {
+ t.Fatalf("Stat returned unexpected file metadata: %#v", stat)
+ }
+ content, err := firstClient.ReadFile(ctx, firstHandle, path)
+ if err != nil {
+ t.Fatalf("ReadFile: %v", err)
+ }
+ if !bytes.Equal(content, payload) {
+ t.Fatalf("ReadFile content mismatch: got=%q want=%q", content, payload)
+ }
+
+ waitForE2BSandboxPause(t, ctx, firstClient, sandboxID, expectedMetadata)
+
+ secondClient := newE2BIntegrationClient(t, cfg)
+ secondLifecycle := newE2BIntegrationLifecycle(t, secondClient, store, createRequest)
+ secondHandle, err := secondLifecycle.Resolve(ctx, key)
+ if err != nil {
+ t.Fatalf("Resolve after simulated process restart: %v", err)
+ }
+ if secondHandle.ID() != sandboxID {
+ t.Fatalf("Resolve after restart returned sandbox %s, want %s", secondHandle.ID(), sandboxID)
+ }
+ content, err = secondClient.ReadFile(ctx, secondHandle, path)
+ if err != nil {
+ t.Fatalf("ReadFile after automatic resume: %v", err)
+ }
+ if !bytes.Equal(content, payload) {
+ t.Fatalf("filesystem state did not survive pause/resume: got=%q want=%q", content, payload)
+ }
+
+ deleted, err := store.DeleteIfMatch(ctx, key, SandboxTypeE2B, sandboxID)
+ if err != nil {
+ t.Fatalf("delete binding while preserving remote sandbox: %v", err)
+ }
+ if !deleted {
+ t.Fatal("binding disappeared before metadata-recovery test")
+ }
+
+ thirdClient := newE2BIntegrationClient(t, cfg)
+ thirdLifecycle := newE2BIntegrationLifecycle(t, thirdClient, store, createRequest)
+ thirdHandle, err := thirdLifecycle.Resolve(ctx, key)
+ if err != nil {
+ t.Fatalf("Resolve after binding loss: %v", err)
+ }
+ if thirdHandle.ID() != sandboxID {
+ t.Fatalf("metadata recovery claimed sandbox %s, want original %s", thirdHandle.ID(), sandboxID)
+ }
+
+ candidates, err := thirdClient.List(ctx, RemoteListFilter{Metadata: expectedMetadata})
+ if err != nil {
+ t.Fatalf("List ownership metadata candidates: %v", err)
+ }
+ nonterminal := make([]RemoteSandboxSummary, 0, len(candidates))
+ for _, candidate := range candidates {
+ if candidate.State != RemoteStateTerminal {
+ nonterminal = append(nonterminal, candidate)
+ }
+ }
+ if len(nonterminal) != 1 || nonterminal[0].ID != sandboxID {
+ t.Fatalf("metadata recovery left non-unique candidates: got=%#v want only %s",
+ nonterminal, sandboxID)
+ }
+
+ if err := thirdClient.Remove(ctx, thirdHandle, path); err != nil {
+ t.Fatalf("Remove file: %v", err)
+ }
+ if err := thirdClient.Remove(ctx, thirdHandle, base); err != nil {
+ t.Fatalf("Remove directory: %v", err)
+ }
+ if err := thirdLifecycle.Destroy(ctx, key); err != nil {
+ t.Fatalf("lifecycle Destroy: %v", err)
+ }
+ binding, err := store.Get(ctx, key)
+ if err != nil {
+ t.Fatalf("read binding after lifecycle Destroy: %v", err)
+ }
+ if binding != nil {
+ t.Fatalf("lifecycle Destroy left binding behind: %#v", binding)
+ }
+ waitForE2BSandboxDeletion(t, ctx, thirdClient, sandboxID)
+ destroyed = true
+}
+
+func e2bIntegrationConfig(t *testing.T) *Config {
+ t.Helper()
+ apiKey := firstNonEmptyEnvironment(
+ "WEKNORA_SANDBOX_E2B_API_KEY",
+ "E2B_API_KEY",
+ )
+ template := firstNonEmptyEnvironment(
+ "WEKNORA_SANDBOX_E2B_TEMPLATE",
+ "E2B_TEMPLATE",
+ )
+ if apiKey == "" || template == "" {
+ t.Skip("E2B integration requires an API key and template")
+ }
+
+ cfg := DefaultConfig()
+ cfg.Type = SandboxTypeE2B
+ cfg.FallbackEnabled = false
+ cfg.E2BAPIKey = apiKey
+ cfg.E2BAPIURL = strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_E2B_API_URL"))
+ cfg.E2BSandboxDomain = strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN"))
+ cfg.E2BTemplate = template
+ cfg.E2BSandboxTTL = e2bIntegrationTTL
+ cfg.E2BHTTPTimeout = e2bIntegrationHTTPTimeout
+ return cfg
+}
+
+func firstNonEmptyEnvironment(names ...string) string {
+ for _, name := range names {
+ if value := strings.TrimSpace(os.Getenv(name)); value != "" {
+ return value
+ }
+ }
+ return ""
+}
+
+func newE2BIntegrationClient(t *testing.T, cfg *Config) *E2BRemoteClient {
+ t.Helper()
+ client, err := NewE2BRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("NewE2BRemoteClient: %v", err)
+ }
+ return client
+}
+
+func newE2BIntegrationLifecycle(
+ t *testing.T,
+ client *E2BRemoteClient,
+ store SessionSandboxBindingStore,
+ createRequest RemoteCreateRequest,
+) *remoteSessionLifecycle {
+ t.Helper()
+ lifecycle, err := newRemoteSessionLifecycle(
+ client,
+ store,
+ PermissiveSessionExistenceChecker{},
+ createRequest,
+ time.Minute,
+ "",
+ )
+ if err != nil {
+ t.Fatalf("newRemoteSessionLifecycle: %v", err)
+ }
+ return lifecycle
+}
+
+func waitForE2BSandboxPause(
+ t *testing.T,
+ parent context.Context,
+ client *E2BRemoteClient,
+ sandboxID string,
+ expectedMetadata map[string]string,
+) {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(parent, e2bIntegrationPauseTimeout)
+ defer cancel()
+ ticker := time.NewTicker(e2bIntegrationPollInterval)
+ defer ticker.Stop()
+
+ var lastState RemoteSandboxState
+ var lastRawState string
+ for {
+ summary, err := client.Get(ctx, sandboxID)
+ if err != nil {
+ t.Fatalf("E2B control plane did not return the sandbox as paused with lifecycle "+
+ "metadata; Get stopped returning sandbox %s before the %s deadline: %v",
+ sandboxID, e2bIntegrationPauseTimeout, err)
+ }
+ if summary == nil {
+ t.Fatal("control-plane Get returned nil while waiting for pause")
+ }
+ lastState = summary.State
+ lastRawState = summary.RawState
+ if summary.State == RemoteStatePaused {
+ if !metadataMatches(summary.Metadata, expectedMetadata) {
+ t.Fatalf("paused sandbox omitted lifecycle metadata: got=%v want=%v",
+ summary.Metadata, expectedMetadata)
+ }
+ return
+ }
+
+ select {
+ case <-ctx.Done():
+ t.Fatalf("E2B control plane did not report paused sandbox with metadata within %s; "+
+ "last state=%s raw_state=%q", e2bIntegrationPauseTimeout, lastState, lastRawState)
+ case <-ticker.C:
+ }
+ }
+}
+
+func waitForE2BSandboxDeletion(
+ t *testing.T,
+ parent context.Context,
+ client *E2BRemoteClient,
+ sandboxID string,
+) {
+ t.Helper()
+ const deletionTimeout = time.Minute
+ ctx, cancel := context.WithTimeout(parent, deletionTimeout)
+ defer cancel()
+ ticker := time.NewTicker(e2bIntegrationPollInterval)
+ defer ticker.Stop()
+
+ var lastState RemoteSandboxState
+ for {
+ summary, err := client.Get(ctx, sandboxID)
+ if IsRemoteNotFound(err) {
+ return
+ }
+ if err != nil {
+ t.Fatalf("Get while verifying lifecycle Destroy: %v", err)
+ }
+ if summary != nil {
+ lastState = summary.State
+ }
+
+ select {
+ case <-ctx.Done():
+ t.Fatalf("E2B sandbox %s remained visible for %s after lifecycle Destroy; "+
+ "last state=%s", sandboxID, deletionTimeout, lastState)
+ case <-ticker.C:
+ }
+ }
+}
diff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.go
new file mode 100644
index 000000000..b6dedfc7e
--- /dev/null
+++ b/internal/sandbox/e2b_remote_client.go
@@ -0,0 +1,890 @@
+// Package sandbox: E2B adapter for the provider-neutral RemoteSandboxClient.
+//
+// E2BRemoteClient wraps go-e2b and keeps provider-specific configuration,
+// lifecycle, access-token, and filesystem details behind RemoteSandboxClient.
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "time"
+
+ "connectrpc.com/connect"
+ e2b "github.com/matiasinsaurralde/go-e2b"
+)
+
+// E2BRemoteClient implements RemoteSandboxClient on top of the go-e2b client.
+type E2BRemoteClient struct {
+ client *e2b.Client
+
+ templateID string
+ timeout time.Duration
+}
+
+// NewE2BRemoteClient builds an E2B-backed RemoteSandboxClient from Config.
+// The API key is required; the caller may leave APIURL / SandboxDomain empty
+// to fall back to the SDK's built-in defaults.
+func NewE2BRemoteClient(cfg *Config) (*E2BRemoteClient, error) {
+ return NewE2BRemoteClientWithTransport(cfg, nil)
+}
+
+// NewE2BRemoteClientWithTransport builds the client with an injected HTTP
+// transport. Per-tenant clients are constructed per request, so sharing one
+// transport across tenants is what preserves connection pooling: transports
+// pool per host:port and the API key travels in per-request headers, making
+// the sharing both safe and effective. A nil transport uses the http default.
+func NewE2BRemoteClientWithTransport(
+ cfg *Config,
+ transport *http.Transport,
+) (*E2BRemoteClient, error) {
+ if cfg == nil {
+ return nil, errors.New("e2b remote client config is required")
+ }
+ if strings.TrimSpace(cfg.E2BAPIKey) == "" {
+ return nil, errors.New("E2BAPIKey is required for the E2B backend")
+ }
+ timeout := cfg.E2BHTTPTimeout
+ if timeout <= 0 {
+ timeout = DefaultE2BHTTPTimeout
+ }
+ httpClient := &http.Client{Timeout: timeout}
+ if transport != nil {
+ httpClient.Transport = transport
+ }
+ client, err := e2b.NewClient(e2b.ClientConfig{
+ APIKey: cfg.E2BAPIKey,
+ APIBaseURL: strings.TrimSpace(cfg.E2BAPIURL),
+ SandboxDomain: strings.TrimSpace(cfg.E2BSandboxDomain),
+ HTTPClient: httpClient,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("build e2b client: %w", err)
+ }
+
+ ttl := cfg.E2BSandboxTTL
+ if ttl <= 0 {
+ ttl = DefaultE2BSandboxTTL
+ }
+ return &E2BRemoteClient{
+ client: client,
+ templateID: strings.TrimSpace(cfg.E2BTemplate),
+ timeout: ttl,
+ }, nil
+}
+
+// e2bRemoteHandle is the RemoteSandboxHandle E2B returns. It carries the
+// *e2b.Sandbox so subsequent envd calls can reuse its access token.
+type e2bRemoteHandle struct {
+ sandbox *e2b.Sandbox
+ metadata map[string]string
+}
+
+func (h *e2bRemoteHandle) ID() string {
+ if h == nil || h.sandbox == nil {
+ return ""
+ }
+ return h.sandbox.ID
+}
+
+func (h *e2bRemoteHandle) Provider() RemoteProvider { return SandboxTypeE2B }
+
+func (h *e2bRemoteHandle) Metadata() map[string]string {
+ if h == nil {
+ return nil
+ }
+ return cloneMetadata(h.metadata)
+}
+
+// --- RemoteSandboxClient ------------------------------------------------------
+
+func (c *E2BRemoteClient) Provider() RemoteProvider { return SandboxTypeE2B }
+
+func (c *E2BRemoteClient) Capabilities() RemoteSandboxCapabilities {
+ return RemoteSandboxCapabilities{
+ SupportsReconnect: true,
+ SupportsMetadata: true,
+ SupportsListSandboxes: true,
+ SupportsPauseResume: true,
+ SupportsTimeoutRefresh: true,
+ SupportsFilesystemEnumeration: true,
+ SupportsVolumes: true,
+ }
+}
+
+// Health probes the E2B control plane via ListSandboxes. The SDK does not
+// expose a dedicated health endpoint, and ListSandboxes is the smallest
+// authenticated call that will detect a bad API key or a dead API.
+func (c *E2BRemoteClient) Health(ctx context.Context) error {
+ if _, err := c.client.ListSandboxes(ctx); err != nil {
+ return normalizeE2BError("Health", err)
+ }
+ return nil
+}
+
+func (c *E2BRemoteClient) Create(
+ ctx context.Context,
+ request RemoteCreateRequest,
+) (RemoteSandboxHandle, error) {
+ template := strings.TrimSpace(request.TemplateID)
+ if template == "" {
+ template = c.templateID
+ }
+ if template == "" {
+ return nil, e2bInvalidRequest("Create", "template ID is required", nil)
+ }
+ timeoutSeconds, err := e2bTimeoutSeconds(request.Timeout, c.timeout)
+ if err != nil {
+ return nil, e2bInvalidRequest("Create", err.Error(), err)
+ }
+ action := request.Timeout.Action
+ if action == "" {
+ action = RemoteOnTimeoutKill
+ }
+ if action != RemoteOnTimeoutKill && action != RemoteOnTimeoutPause {
+ return nil, e2bInvalidRequest(
+ "Create",
+ fmt.Sprintf("unsupported timeout action %q", action),
+ nil,
+ )
+ }
+ if request.Timeout.AutoResume && action != RemoteOnTimeoutPause {
+ return nil, e2bInvalidRequest(
+ "Create",
+ "auto resume requires pause on timeout",
+ nil,
+ )
+ }
+
+ // Translate the neutral RemoteNetworkPolicy to E2B's SDK types. When
+ // the caller supplied no policy at all we fall back to the same
+ // permissive defaults the Cube adapter uses (public egress + public
+ // URL reachability) so upgrading WeKnora deployments do not silently
+ // lose `curl` / `pip` access from inside the sandbox.
+ policy := request.Network
+ if policy.AllowInternetAccess == nil {
+ defaultOn := true
+ policy.AllowInternetAccess = &defaultOn
+ }
+ if policy.AllowPublicTraffic == nil {
+ defaultOn := true
+ policy.AllowPublicTraffic = &defaultOn
+ }
+ config := e2b.SandboxConfig{
+ Template: template,
+ Timeout: timeoutSeconds,
+ EnvVars: cloneMetadata(request.EnvVars),
+ Metadata: cloneMetadata(request.Metadata),
+ Secure: true,
+ AllowInternetAccess: policy.AllowInternetAccess,
+ Network: &e2b.NetworkConfig{
+ AllowPublicTraffic: policy.AllowPublicTraffic,
+ AllowOut: append([]string(nil), policy.AllowOut...),
+ DenyOut: append([]string(nil), policy.DenyOut...),
+ },
+ AutoPause: action == RemoteOnTimeoutPause,
+ VolumeMounts: toE2BVolumeMounts(request.VolumeMounts),
+ }
+ if request.Timeout.AutoResume {
+ autoPauseMemory := true
+ config.AutoPauseMemory = &autoPauseMemory
+ config.AutoResume = &e2b.AutoResumeConfig{Enabled: true}
+ }
+ sandbox, err := c.client.NewSandbox(ctx, config)
+ if err != nil {
+ return nil, normalizeE2BError("Create", err)
+ }
+ if sandbox == nil || strings.TrimSpace(sandbox.ID) == "" {
+ return nil, NewRemoteError(
+ SandboxTypeE2B, "Create", RemoteErrorKindInternal,
+ "e2b returned an empty sandbox handle", nil,
+ )
+ }
+ return &e2bRemoteHandle{
+ sandbox: sandbox,
+ metadata: cloneMetadata(request.Metadata),
+ }, nil
+}
+
+func (c *E2BRemoteClient) Connect(
+ ctx context.Context,
+ sandboxID string,
+) (RemoteSandboxHandle, error) {
+ if strings.TrimSpace(sandboxID) == "" {
+ return nil, e2bInvalidRequest("Connect", "sandbox ID is required", nil)
+ }
+ timeoutSeconds, err := e2bTimeoutSeconds(
+ RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault},
+ c.timeout,
+ )
+ if err != nil {
+ return nil, e2bInvalidRequest("Connect", err.Error(), err)
+ }
+ sandbox, err := c.client.Connect(ctx, sandboxID, timeoutSeconds)
+ if err != nil {
+ return nil, normalizeE2BError("Connect", err)
+ }
+ if sandbox == nil || strings.TrimSpace(sandbox.ID) == "" ||
+ sandbox.ID != sandboxID {
+ return nil, NewRemoteError(
+ SandboxTypeE2B, "Connect", RemoteErrorKindInternal,
+ "e2b returned a mismatched sandbox handle", nil,
+ )
+ }
+ return &e2bRemoteHandle{sandbox: sandbox}, nil
+}
+
+// Get returns a single sandbox summary by ID. E2B's control plane exposes no
+// read-only "fetch sandbox by ID" endpoint, so Get reattaches to the sandbox
+// via Connect and reads its full metadata through the per-sandbox info
+// endpoint (GET /sandboxes/{id}). This mirrors the Cube adapter's
+// Connect+GetInfo shape and yields a strongly-consistent, O(1) lookup with a
+// clean NotFound, instead of scanning the whole account-wide sandbox list
+// (which is O(N) and can return a stale NotFound for a just-created sandbox).
+//
+// Get's only caller is the lifecycle coordinator's connectBinding pre-check,
+// which Connects — and therefore wakes — the sandbox immediately afterwards.
+// Resuming a paused sandbox here is thus the intended behaviour, not a side
+// effect to avoid.
+func (c *E2BRemoteClient) Get(
+ ctx context.Context,
+ sandboxID string,
+) (*RemoteSandboxSummary, error) {
+ if strings.TrimSpace(sandboxID) == "" {
+ return nil, e2bInvalidRequest("Get", "sandbox ID is required", nil)
+ }
+ timeoutSeconds, err := e2bTimeoutSeconds(
+ RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault},
+ c.timeout,
+ )
+ if err != nil {
+ return nil, e2bInvalidRequest("Get", err.Error(), err)
+ }
+ sandbox, err := c.client.Connect(ctx, sandboxID, timeoutSeconds)
+ if err != nil {
+ return nil, normalizeE2BError("Get", err)
+ }
+ if sandbox == nil || strings.TrimSpace(sandbox.ID) == "" ||
+ sandbox.ID != sandboxID {
+ return nil, NewRemoteError(
+ SandboxTypeE2B, "Get", RemoteErrorKindInternal,
+ "e2b returned a mismatched sandbox handle", nil,
+ )
+ }
+ info, err := sandbox.InfoWithContext(ctx)
+ if err != nil {
+ return nil, normalizeE2BError("Get", err)
+ }
+ if info == nil {
+ return nil, NewRemoteError(
+ SandboxTypeE2B, "Get", RemoteErrorKindNotFound,
+ "sandbox not found", nil,
+ )
+ }
+ summary := e2bRemoteSummary(*info)
+ return &summary, nil
+}
+
+func (c *E2BRemoteClient) List(
+ ctx context.Context,
+ filter RemoteListFilter,
+) ([]RemoteSandboxSummary, error) {
+ if len(filter.States) > 0 && len(e2bListStates(filter.States)) == 0 {
+ return []RemoteSandboxSummary{}, nil
+ }
+ infos, err := c.listSandboxesV2(ctx, "List", filter)
+ if err != nil {
+ return nil, err
+ }
+ result := make([]RemoteSandboxSummary, 0, len(infos))
+ for _, info := range infos {
+ converted := e2bRemoteSummary(info)
+ if !metadataMatches(converted.Metadata, filter.Metadata) ||
+ !StateMatches(converted.State, filter.States) {
+ continue
+ }
+ result = append(result, converted)
+ }
+ return result, nil
+}
+
+func (c *E2BRemoteClient) listSandboxesV2(
+ ctx context.Context,
+ op string,
+ filter RemoteListFilter,
+) ([]e2b.SandboxInfo, error) {
+ baseOptions := []e2b.ListSandboxesV2Option{e2b.WithSandboxLimit(100)}
+ if serverMetadata := e2bServerMetadataFilter(filter.Metadata); len(serverMetadata) > 0 {
+ baseOptions = append(baseOptions, e2b.WithSandboxMetadata(serverMetadata))
+ }
+ if states := e2bListStates(filter.States); len(states) > 0 {
+ baseOptions = append(baseOptions, e2b.WithSandboxState(states...))
+ }
+
+ var sandboxes []e2b.SandboxInfo
+ nextToken := ""
+ seenTokens := make(map[string]struct{})
+ for {
+ options := append([]e2b.ListSandboxesV2Option(nil), baseOptions...)
+ if nextToken != "" {
+ options = append(options, e2b.WithSandboxNextToken(nextToken))
+ }
+ page, err := c.client.ListSandboxesV2(ctx, options...)
+ if err != nil {
+ return nil, normalizeE2BError(op, err)
+ }
+ if page == nil {
+ return nil, NewRemoteError(
+ SandboxTypeE2B,
+ op,
+ RemoteErrorKindInternal,
+ "e2b returned an empty sandbox list page",
+ nil,
+ )
+ }
+ sandboxes = append(sandboxes, page.Sandboxes...)
+ if page.NextToken == "" {
+ return sandboxes, nil
+ }
+ if !e2bQuerySafe(page.NextToken) {
+ return nil, NewRemoteError(
+ SandboxTypeE2B,
+ op,
+ RemoteErrorKindInternal,
+ "e2b returned an unsafe sandbox list pagination token",
+ nil,
+ )
+ }
+ if _, repeated := seenTokens[page.NextToken]; repeated {
+ return nil, NewRemoteError(
+ SandboxTypeE2B,
+ op,
+ RemoteErrorKindInternal,
+ "e2b returned a repeated sandbox list pagination token",
+ nil,
+ )
+ }
+ seenTokens[page.NextToken] = struct{}{}
+ nextToken = page.NextToken
+ }
+}
+
+// E2B's V2 endpoint accepts one metadata query parameter even though the SDK
+// option accepts a map. Send the most selective stable ownership key available;
+// List still applies the complete metadata filter locally before returning.
+func e2bServerMetadataFilter(metadata map[string]string) map[string]string {
+ if len(metadata) == 0 {
+ return nil
+ }
+ for _, key := range []string{
+ remoteMetadataSessionID,
+ remoteMetadataTenantID,
+ remoteMetadataProvider,
+ remoteMetadataBindingVersion,
+ remoteMetadataConfigID,
+ } {
+ if value, ok := metadata[key]; ok {
+ return e2bSafeMetadataFilter(key, value)
+ }
+ }
+ keys := make([]string, 0, len(metadata))
+ for key := range metadata {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ key := keys[0]
+ return e2bSafeMetadataFilter(key, metadata[key])
+}
+
+func e2bSafeMetadataFilter(key, value string) map[string]string {
+ if !e2bQuerySafe(key) || !e2bQuerySafe(value) {
+ return nil
+ }
+ return map[string]string{key: value}
+}
+
+func e2bQuerySafe(value string) bool {
+ return url.QueryEscape(value) == value
+}
+
+func e2bListStates(states []RemoteSandboxState) []string {
+ result := make([]string, 0, len(states))
+ for _, state := range states {
+ switch state {
+ case RemoteStateRunning:
+ result = append(result, "running")
+ case RemoteStatePaused:
+ result = append(result, "paused")
+ }
+ }
+ return result
+}
+
+func (c *E2BRemoteClient) Delete(ctx context.Context, sandboxID string) error {
+ if strings.TrimSpace(sandboxID) == "" {
+ return e2bInvalidRequest("Delete", "sandbox ID is required", nil)
+ }
+ timeoutSeconds, err := e2bTimeoutSeconds(
+ RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault},
+ c.timeout,
+ )
+ if err != nil {
+ return e2bInvalidRequest("Delete", err.Error(), err)
+ }
+ sandbox, err := c.client.Connect(ctx, sandboxID, timeoutSeconds)
+ if err != nil {
+ return normalizeE2BError("Delete", err)
+ }
+ if sandbox == nil || strings.TrimSpace(sandbox.ID) == "" ||
+ sandbox.ID != sandboxID {
+ return NewRemoteError(
+ SandboxTypeE2B, "Delete", RemoteErrorKindInternal,
+ "e2b returned a mismatched sandbox handle", nil,
+ )
+ }
+ if err := sandbox.CloseWithContext(ctx); err != nil {
+ return normalizeE2BError("Delete", err)
+ }
+ return nil
+}
+
+func (c *E2BRemoteClient) Exec(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ request RemoteExecRequest,
+) (*RemoteExecResult, error) {
+ sandbox, err := e2bHandleSandbox("Exec", handle)
+ if err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(request.Command) == "" {
+ return nil, e2bInvalidRequest("Exec", "command is required", nil)
+ }
+ if request.Shell && len(request.Args) != 0 {
+ return nil, e2bInvalidRequest(
+ "Exec", "shell execution cannot include argv arguments", nil,
+ )
+ }
+ if request.Timeout < 0 {
+ return nil, e2bInvalidRequest("Exec", "execution timeout cannot be negative", nil)
+ }
+
+ // The SDK runs every command through `/bin/bash -l -c <cmd>`, so argv mode
+ // is lowered to a quoted shell line and stdin (when present) is piped in
+ // via a heredoc. This mirrors the Cube adapter exactly, keeping argv+stdin
+ // working identically across both remote backends.
+ cmd := request.Command
+ if !request.Shell {
+ cmd = buildShellLine(request.Command, request.Args)
+ }
+ if request.Stdin != "" {
+ cmd = wrapWithStdin(cmd, request.Stdin)
+ }
+
+ execCtx := ctx
+ cancel := context.CancelFunc(func() {})
+ if request.Timeout > 0 {
+ execCtx, cancel = context.WithTimeout(ctx, request.Timeout)
+ }
+ defer cancel()
+
+ start := time.Now()
+ options := []e2b.RunOption{}
+ if request.WorkDir != "" {
+ options = append(options, e2b.WithCwd(request.WorkDir))
+ }
+ if len(request.Env) > 0 {
+ options = append(options, e2b.WithEnv(cloneMetadata(request.Env)))
+ }
+ if request.User != "" {
+ options = append(options, e2b.WithUser(request.User))
+ }
+ if request.Timeout > 0 {
+ options = append(options, e2b.WithTimeout(request.Timeout))
+ }
+ result, err := sandbox.Commands.Run(execCtx, cmd, options...)
+ duration := time.Since(start)
+
+ if err != nil {
+ // A timeout is a normal RemoteExecResult with Killed=true, never a
+ // hard error. Detection cannot rely on execCtx.Err() alone: the SDK
+ // derives its own timeout context (from request.Timeout, or from its
+ // DefaultCommandTimeout when we pass none), and when *that* timer
+ // fires it cancels the SDK's child context rather than our execCtx.
+ // The SDK then surfaces every deadline as *e2b.TimeoutError, so we
+ // key off that plus our own deadline to cover whichever timer wins.
+ if isE2BExecTimeout(execCtx, err) {
+ return &RemoteExecResult{
+ Duration: duration,
+ Killed: true,
+ ExitCode: -1,
+ }, nil
+ }
+ // A non-zero exit code is reported by the SDK as *CommandExitError
+ // with the captured output still attached. This is a normal
+ // execution signal (a failing script, `grep` with no match,
+ // `exit 1`), not a wire failure, so lower it to a RemoteExecResult
+ // exactly like the Cube adapter — whose SDK returns the exit code
+ // inline. Only genuine transport/RPC errors fall through to
+ // normalizeE2BError below.
+ var exitErr *e2b.CommandExitError
+ if errors.As(err, &exitErr) {
+ return &RemoteExecResult{
+ Stdout: exitErr.Stdout,
+ Stderr: exitErr.Stderr,
+ ExitCode: exitErr.ExitCode,
+ Duration: duration,
+ }, nil
+ }
+ return nil, normalizeE2BError("Exec", err)
+ }
+ if result == nil {
+ return nil, NewRemoteError(
+ SandboxTypeE2B, "Exec", RemoteErrorKindInternal,
+ "e2b returned an empty command result", nil,
+ )
+ }
+ return &RemoteExecResult{
+ Stdout: result.Stdout,
+ Stderr: result.Stderr,
+ ExitCode: result.ExitCode,
+ Duration: duration,
+ }, nil
+}
+
+func (c *E2BRemoteClient) WriteFile(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+ content []byte,
+) error {
+ sandbox, err := e2bHandleSandbox("WriteFile", handle)
+ if err != nil {
+ return err
+ }
+ if strings.TrimSpace(path) == "" {
+ return e2bInvalidRequest("WriteFile", "path is required", nil)
+ }
+ if _, err := sandbox.Filesystem.WriteBytes(ctx, path, content); err != nil {
+ return normalizeE2BError("WriteFile", err)
+ }
+ return nil
+}
+
+func (c *E2BRemoteClient) ReadFile(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) ([]byte, error) {
+ sandbox, err := e2bHandleSandbox("ReadFile", handle)
+ if err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(path) == "" {
+ return nil, e2bInvalidRequest("ReadFile", "path is required", nil)
+ }
+ content, err := sandbox.Filesystem.ReadBytes(ctx, path)
+ if err != nil {
+ return nil, normalizeE2BError("ReadFile", err)
+ }
+ return content, nil
+}
+
+func (c *E2BRemoteClient) ListDir(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) ([]RemoteDirEntry, error) {
+ sandbox, err := e2bHandleSandbox("ListDir", handle)
+ if err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(path) == "" {
+ return nil, e2bInvalidRequest("ListDir", "path is required", nil)
+ }
+ entries, err := sandbox.Filesystem.List(ctx, path)
+ if err != nil {
+ return nil, normalizeE2BError("ListDir", err)
+ }
+ result := make([]RemoteDirEntry, 0, len(entries))
+ for _, e := range entries {
+ result = append(result, RemoteDirEntry{
+ Name: e.Name,
+ Path: e.Path,
+ Type: e2bRemoteEntryType(e.Type),
+ Size: e.Size,
+ ModTime: e.ModTime,
+ })
+ }
+ return result, nil
+}
+
+func (c *E2BRemoteClient) MakeDir(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) error {
+ sandbox, err := e2bHandleSandbox("MakeDir", handle)
+ if err != nil {
+ return err
+ }
+ if strings.TrimSpace(path) == "" {
+ return e2bInvalidRequest("MakeDir", "path is required", nil)
+ }
+ if err := sandbox.Filesystem.MakeDir(ctx, path); err != nil {
+ return normalizeE2BError("MakeDir", err)
+ }
+ return nil
+}
+
+func (c *E2BRemoteClient) Remove(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) error {
+ sandbox, err := e2bHandleSandbox("Remove", handle)
+ if err != nil {
+ return err
+ }
+ if strings.TrimSpace(path) == "" {
+ return e2bInvalidRequest("Remove", "path is required", nil)
+ }
+ if err := sandbox.Filesystem.Remove(ctx, path); err != nil {
+ return normalizeE2BError("Remove", err)
+ }
+ return nil
+}
+
+func (c *E2BRemoteClient) Stat(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ path string,
+) (*RemoteStatEntry, error) {
+ sandbox, err := e2bHandleSandbox("Stat", handle)
+ if err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(path) == "" {
+ return nil, e2bInvalidRequest("Stat", "path is required", nil)
+ }
+ info, err := sandbox.Filesystem.Stat(ctx, path)
+ if err != nil {
+ return nil, normalizeE2BError("Stat", err)
+ }
+ if info == nil {
+ return nil, NewRemoteError(
+ SandboxTypeE2B, "Stat", RemoteErrorKindNotFound,
+ "path not found", nil,
+ )
+ }
+ return &RemoteStatEntry{
+ Path: info.Path,
+ Type: e2bRemoteEntryType(info.Type),
+ Size: info.Size,
+ ModTime: info.ModTime,
+ }, nil
+}
+
+// --- helpers -----------------------------------------------------------------
+
+// e2bTimeoutSeconds maps the neutral RemoteTimeoutPolicy onto E2B's integer
+// timeout. E2B only supports a positive TTL; "never" is rejected as
+// unsupported so the lifecycle coordinator can pick a different policy.
+func e2bTimeoutSeconds(policy RemoteTimeoutPolicy, fallback time.Duration) (int, error) {
+ toSeconds := func(value time.Duration) (int, error) {
+ if value > 0 && value < time.Second {
+ return 0, errors.New("E2B timeout must be at least one second")
+ }
+ seconds := value / time.Second
+ if value%time.Second != 0 {
+ seconds++
+ }
+ return int(seconds), nil
+ }
+
+ switch policy.Mode {
+ case "", RemoteTimeoutServerDefault:
+ if fallback <= 0 {
+ return 0, nil
+ }
+ return toSeconds(fallback)
+ case RemoteTimeoutExplicit:
+ if policy.Value < 0 {
+ return 0, errors.New("E2B backend does not support NeverTimeout")
+ }
+ return toSeconds(policy.Value)
+ default:
+ return 0, fmt.Errorf("unsupported timeout mode %q", policy.Mode)
+ }
+}
+
+// toE2BVolumeMounts converts the provider-neutral RemoteVolumeMount slice to
+// E2B SDK VolumeMount values. Nil and empty inputs both produce nil.
+func toE2BVolumeMounts(src []RemoteVolumeMount) []e2b.VolumeMount {
+ if len(src) == 0 {
+ return nil
+ }
+ result := make([]e2b.VolumeMount, len(src))
+ for i, mount := range src {
+ result[i] = e2b.VolumeMount{
+ Name: mount.Name,
+ Path: mount.Path,
+ }
+ }
+ return result
+}
+
+// isE2BExecTimeout reports whether a failed command Run should be treated as
+// a timeout kill (Killed=true) rather than a transport error. It recognises:
+// - our own execCtx deadline (request.Timeout);
+// - a raw context deadline returned before the stream was established;
+// - *e2b.TimeoutError, which the SDK returns for both its internal command
+// timeout and any Connect deadline surfaced from the envd stream.
+func isE2BExecTimeout(execCtx context.Context, err error) bool {
+ if errors.Is(execCtx.Err(), context.DeadlineExceeded) {
+ return true
+ }
+ if errors.Is(err, context.DeadlineExceeded) {
+ return true
+ }
+ var timeoutErr *e2b.TimeoutError
+ return errors.As(err, &timeoutErr)
+}
+
+func e2bHandleSandbox(op string, handle RemoteSandboxHandle) (*e2b.Sandbox, error) {
+ h, ok := handle.(*e2bRemoteHandle)
+ if !ok || h == nil || h.sandbox == nil {
+ return nil, e2bInvalidRequest(op, "handle was not issued by E2B", nil)
+ }
+ return h.sandbox, nil
+}
+
+func e2bRemoteSummary(info e2b.SandboxInfo) RemoteSandboxSummary {
+ startedAt, _ := time.Parse(time.RFC3339, info.StartedAt)
+ endAt, _ := time.Parse(time.RFC3339, info.EndAt)
+ return RemoteSandboxSummary{
+ ID: info.ID,
+ TemplateID: info.Template,
+ State: normalizeE2BState(info.State),
+ RawState: info.State,
+ Metadata: cloneMetadata(info.Metadata),
+ StartedAt: startedAt,
+ EndAt: endAt,
+ }
+}
+
+func normalizeE2BState(state string) RemoteSandboxState {
+ switch strings.ToLower(strings.TrimSpace(state)) {
+ case "running":
+ return RemoteStateRunning
+ case "paused":
+ return RemoteStatePaused
+ case "pending", "creating", "provisioning", "starting", "pausing", "resuming":
+ return RemoteStateTransitioning
+ case "killed", "stopped", "terminated", "deleted", "failed", "error":
+ return RemoteStateTerminal
+ default:
+ return RemoteStateUnknown
+ }
+}
+
+func e2bInvalidRequest(op, message string, cause error) error {
+ return NewRemoteError(
+ SandboxTypeE2B, op, RemoteErrorKindInvalidRequest, message, cause,
+ )
+}
+
+func normalizeE2BError(op string, err error) error {
+ if err == nil {
+ return nil
+ }
+ if errors.Is(err, context.Canceled) {
+ return fmt.Errorf("e2b %s: %w", op, err)
+ }
+ kind := RemoteErrorKindInternal
+ switch {
+ case errors.Is(err, context.DeadlineExceeded):
+ kind = RemoteErrorKindTimeout
+ default:
+ var sandboxNotFound *e2b.SandboxNotFoundError
+ var fileNotFound *e2b.FileNotFoundError
+ var templateNotFound *e2b.TemplateNotFoundError
+ var invalidArg *e2b.InvalidArgumentError
+ var authErr *e2b.AuthenticationError
+ var apiErr *e2b.Error
+ var timeoutErr *e2b.TimeoutError
+ var connectErr *connect.Error
+ var networkErr net.Error
+ switch {
+ case errors.As(err, &sandboxNotFound):
+ kind = RemoteErrorKindNotFound
+ case errors.As(err, &fileNotFound):
+ kind = RemoteErrorKindNotFound
+ case errors.As(err, &templateNotFound):
+ kind = RemoteErrorKindInvalidRequest
+ // The envd process/filesystem RPC layer converts Connect codes into
+ // these typed errors (see the SDK's mapProcessRPCError), so they
+ // never reach the *connect.Error branch below. Match them explicitly
+ // or they would fall through to the default RemoteErrorKindInternal.
+ case errors.As(err, &invalidArg):
+ kind = RemoteErrorKindInvalidRequest
+ case errors.As(err, &authErr):
+ kind = RemoteErrorKindAuthentication
+ case errors.As(err, &timeoutErr):
+ kind = RemoteErrorKindTimeout
+ case errors.As(err, &apiErr):
+ kind = httpErrorKind(op, apiErr.StatusCode)
+ case errors.As(err, &connectErr):
+ switch connectErr.Code() {
+ case connect.CodeCanceled, connect.CodeDeadlineExceeded:
+ kind = RemoteErrorKindTimeout
+ case connect.CodeUnavailable:
+ kind = RemoteErrorKindUnavailable
+ case connect.CodeUnauthenticated, connect.CodePermissionDenied:
+ kind = RemoteErrorKindAuthentication
+ case connect.CodeResourceExhausted:
+ kind = RemoteErrorKindCapacity
+ case connect.CodeInvalidArgument, connect.CodeOutOfRange:
+ kind = RemoteErrorKindInvalidRequest
+ case connect.CodeNotFound:
+ kind = RemoteErrorKindNotFound
+ case connect.CodeAlreadyExists, connect.CodeAborted, connect.CodeFailedPrecondition:
+ kind = RemoteErrorKindConflict
+ case connect.CodeUnimplemented:
+ kind = RemoteErrorKindUnsupported
+ case connect.CodeInternal, connect.CodeDataLoss, connect.CodeUnknown:
+ kind = RemoteErrorKindInternal
+ }
+ case errors.As(err, &networkErr):
+ if networkErr.Timeout() {
+ kind = RemoteErrorKindTimeout
+ } else {
+ kind = RemoteErrorKindUnavailable
+ }
+ }
+ }
+ return NewRemoteError(SandboxTypeE2B, op, kind, err.Error(), err)
+}
+
+// e2bRemoteEntryType maps the E2B SDK FileInfo.Type onto the provider-neutral
+// RemoteDirEntryType.
+func e2bRemoteEntryType(fileType string) RemoteDirEntryType {
+ switch strings.ToLower(strings.TrimSpace(fileType)) {
+ case "file":
+ return RemoteEntryFile
+ case "directory", "dir":
+ return RemoteEntryDir
+ default:
+ return RemoteEntryOther
+ }
+}
+
+var (
+ _ RemoteSandboxClient = (*E2BRemoteClient)(nil)
+ _ RemoteSandboxHandle = (*e2bRemoteHandle)(nil)
+)
diff --git a/internal/sandbox/e2b_remote_client_test.go b/internal/sandbox/e2b_remote_client_test.go
new file mode 100644
index 000000000..dbf5d19ce
--- /dev/null
+++ b/internal/sandbox/e2b_remote_client_test.go
@@ -0,0 +1,919 @@
+package sandbox
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "connectrpc.com/connect"
+ e2b "github.com/matiasinsaurralde/go-e2b"
+ "github.com/stretchr/testify/require"
+)
+
+type e2bTestNetError struct {
+ timeout bool
+}
+
+func (e e2bTestNetError) Error() string { return "network failure" }
+func (e e2bTestNetError) Timeout() bool { return e.timeout }
+func (e e2bTestNetError) Temporary() bool { return false }
+
+var _ net.Error = e2bTestNetError{}
+
+// e2bMockServer emulates the E2B control-plane endpoints used by
+// E2BRemoteClient. Per-sandbox envd traffic is outside this mock.
+type e2bMockServer struct {
+ server *httptest.Server
+
+ createCount atomic.Int32
+ listCount atomic.Int32
+ v2ListCount atomic.Int32
+ connectCount atomic.Int32
+ infoCount atomic.Int32
+ deleteCount atomic.Int32
+
+ nextID atomic.Int64
+ createBody map[string]any
+ connectBody map[string]any
+ connectID string
+ deleteID string
+
+ mu sync.Mutex
+ v2Queries []url.Values
+ repeatV2NextToken bool
+ unsafeV2NextToken string
+ sandboxes map[string]map[string]any // sandboxID → SandboxInfo JSON
+}
+
+func newE2BMockServer(t *testing.T) *e2bMockServer {
+ t.Helper()
+ m := &e2bMockServer{sandboxes: map[string]map[string]any{}}
+ m.server = httptest.NewServer(http.HandlerFunc(m.handle))
+ t.Cleanup(m.server.Close)
+ return m
+}
+
+func (m *e2bMockServer) URL() string { return m.server.URL }
+
+func (m *e2bMockServer) handle(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/sandboxes" && r.Method == http.MethodPost:
+ m.createCount.Add(1)
+ body, _ := io.ReadAll(r.Body)
+ _ = json.Unmarshal(body, &m.createBody)
+ id := "e2b-" + strconv.FormatInt(m.nextID.Add(1), 10)
+ m.sandboxes[id] = map[string]any{
+ "sandboxID": id,
+ "templateID": m.createBody["templateID"],
+ "state": "running",
+ "envdVersion": "test",
+ "startedAt": time.Now().UTC().Format(time.RFC3339),
+ "metadata": m.createBody["metadata"],
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "sandboxID": id,
+ "envdAccessToken": "token-" + id,
+ })
+
+ case r.URL.Path == "/sandboxes" && r.Method == http.MethodGet:
+ m.listCount.Add(1)
+ items := make([]map[string]any, 0, len(m.sandboxes))
+ for _, info := range m.sandboxes {
+ if info["state"] == "running" {
+ items = append(items, info)
+ }
+ }
+ writeJSON(w, http.StatusOK, items)
+
+ case r.URL.Path == "/v2/sandboxes" && r.Method == http.MethodGet:
+ m.handleListV2(w, r)
+
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") &&
+ strings.HasSuffix(r.URL.Path, "/connect") &&
+ r.Method == http.MethodPost:
+ id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/sandboxes/"), "/connect")
+ info, ok := m.sandboxes[id]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ m.connectCount.Add(1)
+ m.connectID = id
+ _ = json.NewDecoder(r.Body).Decode(&m.connectBody)
+ info["state"] = "running"
+ writeJSON(w, http.StatusOK, map[string]any{
+ "sandboxID": id,
+ "envdAccessToken": "reconnected-token-" + id,
+ })
+
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") &&
+ !strings.HasSuffix(r.URL.Path, "/connect") &&
+ r.Method == http.MethodGet:
+ // Per-sandbox info endpoint (GET /sandboxes/{id}). Read-only: it
+ // reports the stored state without mutating it.
+ id := strings.TrimPrefix(r.URL.Path, "/sandboxes/")
+ info, ok := m.sandboxes[id]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ m.infoCount.Add(1)
+ writeJSON(w, http.StatusOK, info)
+
+ case strings.HasPrefix(r.URL.Path, "/sandboxes/") && r.Method == http.MethodDelete:
+ id := strings.TrimPrefix(r.URL.Path, "/sandboxes/")
+ if _, ok := m.sandboxes[id]; !ok {
+ http.NotFound(w, r)
+ return
+ }
+ m.deleteCount.Add(1)
+ m.deleteID = id
+ delete(m.sandboxes, id)
+ w.WriteHeader(http.StatusNoContent)
+
+ default:
+ http.NotFound(w, r)
+ }
+}
+
+func (m *e2bMockServer) handleListV2(w http.ResponseWriter, r *http.Request) {
+ m.v2ListCount.Add(1)
+ m.mu.Lock()
+ m.v2Queries = append(m.v2Queries, r.URL.Query())
+ repeatToken := m.repeatV2NextToken
+ unsafeToken := m.unsafeV2NextToken
+ m.mu.Unlock()
+ if len(r.URL.Query()["metadata"]) > 1 {
+ writeJSON(w, http.StatusBadRequest, map[string]any{
+ "code": http.StatusBadRequest,
+ "message": "metadata accepts a single value",
+ })
+ return
+ }
+
+ states := make(map[string]bool)
+ for _, state := range r.URL.Query()["state"] {
+ states[state] = true
+ }
+ metadata := make(map[string]string)
+ for _, item := range r.URL.Query()["metadata"] {
+ key, value, ok := strings.Cut(item, "=")
+ if ok {
+ metadata[key] = value
+ }
+ }
+
+ ids := make([]string, 0, len(m.sandboxes))
+ for id, info := range m.sandboxes {
+ state, _ := info["state"].(string)
+ if len(states) > 0 && !states[state] {
+ continue
+ }
+ if len(states) == 0 && state != "running" && state != "paused" {
+ continue
+ }
+ if !mockMetadataMatches(info["metadata"], metadata) {
+ continue
+ }
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+
+ limit := 100
+ if raw := r.URL.Query().Get("limit"); raw != "" {
+ if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 {
+ limit = parsed
+ }
+ }
+ start := 0
+ if raw := r.URL.Query().Get("nextToken"); raw != "" && raw != "repeat" {
+ start, _ = strconv.Atoi(raw)
+ }
+ if start > len(ids) {
+ start = len(ids)
+ }
+ end := start + limit
+ if end > len(ids) {
+ end = len(ids)
+ }
+ items := make([]map[string]any, 0, end-start)
+ for _, id := range ids[start:end] {
+ items = append(items, m.sandboxes[id])
+ }
+ if unsafeToken != "" {
+ w.Header().Set("X-Next-Token", unsafeToken)
+ } else if repeatToken {
+ w.Header().Set("X-Next-Token", "repeat")
+ } else if end < len(ids) {
+ w.Header().Set("X-Next-Token", strconv.Itoa(end))
+ }
+ writeJSON(w, http.StatusOK, items)
+}
+
+func mockMetadataMatches(raw any, expected map[string]string) bool {
+ if len(expected) == 0 {
+ return true
+ }
+ actual, ok := raw.(map[string]any)
+ if !ok {
+ return false
+ }
+ for key, value := range expected {
+ if actual[key] != value {
+ return false
+ }
+ }
+ return true
+}
+
+func newTestE2BRemoteClient(t *testing.T, mock *e2bMockServer) *E2BRemoteClient {
+ t.Helper()
+ cfg := &Config{
+ E2BAPIKey: "key-test",
+ E2BAPIURL: mock.URL(),
+ E2BTemplate: "template-a",
+ E2BSandboxTTL: 10 * time.Minute,
+ }
+ client, err := NewE2BRemoteClient(cfg)
+ require.NoError(t, err)
+ return client
+}
+
+func TestE2BRemoteClientProviderAndCapabilities(t *testing.T) {
+ client := newTestE2BRemoteClient(t, newE2BMockServer(t))
+
+ require.Equal(t, SandboxTypeE2B, client.Provider())
+ caps := client.Capabilities()
+ require.True(t, caps.SupportsReconnect)
+ require.True(t, caps.SupportsMetadata)
+ require.True(t, caps.SupportsListSandboxes)
+ require.True(t, caps.SupportsPauseResume)
+ require.True(t, caps.SupportsTimeoutRefresh)
+ // The go-e2b SDK now supports ListDir/Stat/MakeDir/Remove via a
+ // forked SDK (replaced in go.mod). Filesystem enumeration is enabled.
+ require.True(t, caps.SupportsFilesystemEnumeration)
+}
+
+func TestE2BRemoteClientCreateWritesMetadataAndPauseLifecycle(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ metadata := map[string]string{"owner": "session-1"}
+
+ handle, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: 15 * time.Minute,
+ Action: RemoteOnTimeoutPause,
+ AutoResume: true,
+ },
+ Metadata: metadata,
+ EnvVars: map[string]string{"LANG": "C.UTF-8"},
+ })
+ require.NoError(t, err)
+ require.NotEmpty(t, handle.ID())
+ require.Equal(t, SandboxTypeE2B, handle.Provider())
+ require.Equal(t, metadata, handle.Metadata())
+ metadata["owner"] = "mutated-request"
+ handle.Metadata()["owner"] = "mutated-return"
+ require.Equal(t, "session-1", handle.Metadata()["owner"])
+ require.Equal(t, "template-a", mock.createBody["templateID"])
+ require.Equal(t, float64(900), mock.createBody["timeout"])
+ require.Equal(t, map[string]any{"LANG": "C.UTF-8"}, mock.createBody["envVars"])
+ require.Equal(t, map[string]any{"owner": "session-1"}, mock.createBody["metadata"])
+ require.Equal(t, true, mock.createBody["autoPause"])
+ require.Equal(t, true, mock.createBody["autoPauseMemory"])
+ require.Equal(t, map[string]any{"enabled": true}, mock.createBody["autoResume"])
+ // Network defaults match the Cube adapter: public traffic on, internet
+ // egress on, and Secure=true so the response carries an envd access
+ // token. Regressing these keeps `pip install` broken silently, so we
+ // pin the wire payload here.
+ require.Equal(t, true, mock.createBody["secure"])
+ require.Equal(t, true, mock.createBody["allow_internet_access"])
+ networkPayload, ok := mock.createBody["network"].(map[string]any)
+ require.True(t, ok, "network payload missing: %#v", mock.createBody["network"])
+ require.Equal(t, true, networkPayload["allowPublicTraffic"])
+
+}
+
+func TestE2BRemoteClientCreateValidatesTimeoutAction(t *testing.T) {
+ tests := []struct {
+ name string
+ action RemoteTimeoutAction
+ autoResume bool
+ wantError bool
+ }{
+ {name: "default is kill"},
+ {name: "explicit kill", action: RemoteOnTimeoutKill},
+ {name: "invalid action", action: RemoteTimeoutAction("hibernate"), wantError: true},
+ {name: "kill with auto resume", action: RemoteOnTimeoutKill, autoResume: true, wantError: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Action: tt.action,
+ AutoResume: tt.autoResume,
+ },
+ })
+ if tt.wantError {
+ require.True(t, IsRemoteInvalidRequest(err))
+ require.Zero(t, mock.createCount.Load())
+ return
+ }
+ require.NoError(t, err)
+ require.NotContains(t, mock.createBody, "autoPause")
+ require.NotContains(t, mock.createBody, "autoResume")
+ })
+ }
+}
+
+func TestE2BRemoteClientCreateForwardsNetworkPolicy(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ deny := false
+ privateSandbox := false
+
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Network: RemoteNetworkPolicy{
+ AllowInternetAccess: &deny,
+ AllowPublicTraffic: &privateSandbox,
+ AllowOut: []string{"*.example.com"},
+ DenyOut: []string{"0.0.0.0/0"},
+ },
+ })
+ require.NoError(t, err)
+
+ // Top-level allow_internet_access flips off as the caller requested,
+ // AllowPublicTraffic hides the sandbox behind a traffic access token,
+ // and the L3/L4 allow/deny lists both reach the server. Regressing any
+ // of these silently opens (or closes) the sandbox's network policy in
+ // a way callers cannot observe from unit tests, so pin the wire.
+ require.Equal(t, false, mock.createBody["allow_internet_access"])
+ networkPayload, ok := mock.createBody["network"].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, false, networkPayload["allowPublicTraffic"])
+ require.Equal(t, []any{"*.example.com"}, networkPayload["allowOut"])
+ require.Equal(t, []any{"0.0.0.0/0"}, networkPayload["denyOut"])
+}
+
+func TestE2BRemoteClientCreatePreservesTimeoutModes(t *testing.T) {
+ t.Run("server default falls back to config TTL", func(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutServerDefault,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ require.NoError(t, err)
+ require.Equal(t, float64(600), mock.createBody["timeout"])
+ })
+
+ t.Run("never rejected", func(t *testing.T) {
+ client := newTestE2BRemoteClient(t, newE2BMockServer(t))
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: -time.Hour,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ require.True(t, IsRemoteInvalidRequest(err))
+ })
+
+ t.Run("missing template rejected before wire", func(t *testing.T) {
+ cfg := &Config{E2BAPIKey: "key-test", E2BAPIURL: newE2BMockServer(t).URL()}
+ client, err := NewE2BRemoteClient(cfg)
+ require.NoError(t, err)
+ _, err = client.Create(context.Background(), RemoteCreateRequest{})
+ require.True(t, IsRemoteInvalidRequest(err))
+ })
+}
+
+func TestE2BTimeoutSeconds(t *testing.T) {
+ tests := []struct {
+ name string
+ policy RemoteTimeoutPolicy
+ fallback time.Duration
+ want int
+ wantErr bool
+ }{
+ {
+ name: "zero fallback uses SDK default",
+ policy: RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault},
+ fallback: 0,
+ },
+ {
+ name: "sub-second fallback rejected",
+ policy: RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault},
+ fallback: 999 * time.Millisecond,
+ wantErr: true,
+ },
+ {
+ name: "fallback rounds up",
+ policy: RemoteTimeoutPolicy{Mode: RemoteTimeoutServerDefault},
+ fallback: 1500 * time.Millisecond,
+ want: 2,
+ },
+ {
+ name: "zero explicit uses SDK default",
+ policy: RemoteTimeoutPolicy{Mode: RemoteTimeoutExplicit},
+ },
+ {
+ name: "sub-second explicit rejected",
+ policy: RemoteTimeoutPolicy{Mode: RemoteTimeoutExplicit, Value: time.Millisecond},
+ wantErr: true,
+ },
+ {
+ name: "explicit rounds up",
+ policy: RemoteTimeoutPolicy{Mode: RemoteTimeoutExplicit, Value: 1500 * time.Millisecond},
+ want: 2,
+ },
+ {
+ name: "never rejected",
+ policy: RemoteTimeoutPolicy{Mode: RemoteTimeoutExplicit, Value: -time.Second},
+ wantErr: true,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := e2bTimeoutSeconds(tt.policy, tt.fallback)
+ if tt.wantErr {
+ require.Error(t, err)
+ return
+ }
+ require.NoError(t, err)
+ require.Equal(t, tt.want, got)
+ })
+ }
+}
+
+func TestE2BRemoteClientCreateRejectsSubSecondTimeout(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+
+ _, err := client.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: time.Millisecond,
+ },
+ })
+
+ require.True(t, IsRemoteInvalidRequest(err))
+ require.Zero(t, mock.createCount.Load())
+}
+
+func TestE2BRemoteClientConnectAcrossClients(t *testing.T) {
+ mock := newE2BMockServer(t)
+ first := newTestE2BRemoteClient(t, mock)
+ handle, err := first.Create(context.Background(), RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "session-1"},
+ })
+ require.NoError(t, err)
+ mock.sandboxes[handle.ID()]["state"] = "paused"
+
+ second := newTestE2BRemoteClient(t, mock)
+ reconnected, err := second.Connect(context.Background(), handle.ID())
+ require.NoError(t, err)
+ require.Equal(t, handle.ID(), reconnected.ID())
+ require.Nil(t, reconnected.Metadata())
+ require.Equal(t, handle.ID(), mock.connectID)
+ require.Equal(t, int32(1), mock.connectCount.Load())
+ require.Equal(t, float64(600), mock.connectBody["timeout"])
+ require.Equal(t, "running", mock.sandboxes[handle.ID()]["state"])
+}
+
+func TestE2BRemoteClientListFiltersByMetadataAndState(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+
+ _, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "wanted"},
+ })
+ require.NoError(t, err)
+ // A matching paused sandbox proves the state filter is applied after
+ // metadata conversion.
+ paused, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "wanted"},
+ })
+ require.NoError(t, err)
+ mock.sandboxes[paused.ID()]["state"] = "paused"
+ // A running sandbox with different metadata proves both filters are
+ // required for a match.
+ _, err = client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "other"},
+ })
+ require.NoError(t, err)
+
+ running, err := client.List(ctx, RemoteListFilter{
+ Metadata: map[string]string{"owner": "wanted"},
+ States: []RemoteSandboxState{RemoteStateRunning},
+ })
+ require.NoError(t, err)
+ require.Len(t, running, 1)
+ require.Equal(t, RemoteStateRunning, running[0].State)
+ require.Equal(t, map[string]string{"owner": "wanted"}, running[0].Metadata)
+ require.Equal(t, int32(1), mock.v2ListCount.Load())
+ require.Zero(t, mock.listCount.Load(), "List must use the V2 endpoint")
+ require.Equal(t, []string{"running"}, mock.v2Queries[0]["state"])
+ require.Equal(t, []string{"owner=wanted"}, mock.v2Queries[0]["metadata"])
+ require.Equal(t, "100", mock.v2Queries[0].Get("limit"))
+
+ pausedOnly, err := client.List(ctx, RemoteListFilter{
+ Metadata: map[string]string{"owner": "wanted"},
+ States: []RemoteSandboxState{RemoteStatePaused},
+ })
+ require.NoError(t, err)
+ require.Len(t, pausedOnly, 1)
+ require.Equal(t, RemoteStatePaused, pausedOnly[0].State)
+ require.Equal(t, []string{"paused"}, mock.v2Queries[1]["state"])
+
+ all, err := client.List(ctx, RemoteListFilter{
+ Metadata: map[string]string{"owner": "wanted"},
+ })
+ require.NoError(t, err)
+ require.Len(t, all, 2)
+ require.Equal(t, RemoteStateRunning, all[0].State)
+ require.Equal(t, RemoteStatePaused, all[1].State)
+ require.Empty(t, mock.v2Queries[2]["state"], "empty state filter must request V2 defaults")
+}
+
+func TestE2BRemoteClientListUsesOneServerMetadataFilterAndMatchesAllLocally(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+
+ _, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "wanted", "scope": "alpha"},
+ })
+ require.NoError(t, err)
+ _, err = client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{"owner": "wanted", "scope": "beta"},
+ })
+ require.NoError(t, err)
+
+ summaries, err := client.List(ctx, RemoteListFilter{
+ Metadata: map[string]string{"owner": "wanted", "scope": "alpha"},
+ })
+ require.NoError(t, err)
+ require.Len(t, summaries, 1)
+ require.Equal(t, map[string]string{"owner": "wanted", "scope": "alpha"}, summaries[0].Metadata)
+ require.Len(t, mock.v2Queries[0]["metadata"], 1)
+}
+
+func TestE2BRemoteClientListDoesNotClaimSameSessionAcrossTenants(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+ targetMetadata := map[string]string{
+ remoteMetadataTenantID: "tenant-a",
+ remoteMetadataSessionID: "shared-session",
+ remoteMetadataProvider: string(SandboxTypeE2B),
+ remoteMetadataBindingVersion: "1",
+ }
+ otherTenantMetadata := cloneMetadata(targetMetadata)
+ otherTenantMetadata[remoteMetadataTenantID] = "tenant-b"
+
+ target, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: targetMetadata,
+ })
+ require.NoError(t, err)
+ _, err = client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: otherTenantMetadata,
+ })
+ require.NoError(t, err)
+
+ summaries, err := client.List(ctx, RemoteListFilter{Metadata: targetMetadata})
+ require.NoError(t, err)
+ require.Len(t, summaries, 1)
+ require.Equal(t, target.ID(), summaries[0].ID)
+ require.Equal(t, "tenant-a", summaries[0].Metadata[remoteMetadataTenantID])
+ require.Equal(
+ t,
+ []string{remoteMetadataSessionID + "=shared-session"},
+ mock.v2Queries[0]["metadata"],
+ "server query must narrow by session only; complete ownership filtering is local",
+ )
+}
+
+func TestE2BRemoteClientListSkipsUnsafeServerMetadataAndMatchesLocally(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+ unsafeKey := "owner&+=%"
+ unsafeValue := "value&+=%"
+
+ _, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{unsafeKey: unsafeValue},
+ })
+ require.NoError(t, err)
+ _, err = client.Create(ctx, RemoteCreateRequest{
+ TemplateID: "template-a",
+ Metadata: map[string]string{unsafeKey: "other"},
+ })
+ require.NoError(t, err)
+
+ summaries, err := client.List(ctx, RemoteListFilter{
+ Metadata: map[string]string{unsafeKey: unsafeValue},
+ })
+ require.NoError(t, err)
+ require.Len(t, summaries, 1)
+ require.Equal(t, map[string]string{unsafeKey: unsafeValue}, summaries[0].Metadata)
+ require.Empty(t, mock.v2Queries[0]["metadata"])
+}
+
+func TestE2BRemoteClientListSkipsWireForUnmappableStates(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+
+ summaries, err := client.List(context.Background(), RemoteListFilter{
+ States: []RemoteSandboxState{RemoteStateTerminal, RemoteStateUnknown},
+ })
+ require.NoError(t, err)
+ require.Empty(t, summaries)
+ require.Zero(t, mock.v2ListCount.Load())
+}
+
+func TestE2BRemoteClientListMapsKnownStatesFromMixedFilter(t *testing.T) {
+ mock := newE2BMockServer(t)
+ mock.sandboxes["running"] = map[string]any{"sandboxID": "running", "state": "running"}
+ mock.sandboxes["paused"] = map[string]any{"sandboxID": "paused", "state": "paused"}
+ client := newTestE2BRemoteClient(t, mock)
+
+ summaries, err := client.List(context.Background(), RemoteListFilter{
+ States: []RemoteSandboxState{RemoteStateRunning, RemoteStateUnknown},
+ })
+ require.NoError(t, err)
+ require.Len(t, summaries, 1)
+ require.Equal(t, "running", summaries[0].ID)
+ require.Equal(t, int32(1), mock.v2ListCount.Load())
+ require.Equal(t, []string{"running"}, mock.v2Queries[0]["state"])
+}
+
+func TestE2BRemoteSummaryClonesMetadata(t *testing.T) {
+ source := map[string]string{"owner": "session-1"}
+ summary := e2bRemoteSummary(e2b.SandboxInfo{ID: "e2b-1", Metadata: source})
+ source["owner"] = "mutated-source"
+ require.Equal(t, "session-1", summary.Metadata["owner"])
+ summary.Metadata["owner"] = "mutated-summary"
+ require.Equal(t, "mutated-source", source["owner"])
+}
+
+func TestE2BRemoteClientGetUsesConnectAndInfo(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+ handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+
+ summary, err := client.Get(ctx, handle.ID())
+ require.NoError(t, err)
+ require.Equal(t, handle.ID(), summary.ID)
+ require.Equal(t, RemoteStateRunning, summary.State)
+ // TemplateID only comes from the info endpoint; Connect alone cannot
+ // supply it, so its presence proves Get fetched full info by ID.
+ require.Equal(t, "template-a", summary.TemplateID)
+ require.Equal(t, int32(1), mock.connectCount.Load(), "Get reattaches via Connect")
+ require.Equal(t, int32(1), mock.infoCount.Load(), "Get reads info by ID")
+ require.Zero(t, mock.listCount.Load(), "Get must not scan the sandbox list")
+ require.Zero(t, mock.v2ListCount.Load(), "Get must not scan the V2 sandbox list")
+
+ // Unknown ID is a NotFound: Connect 404s and is normalized to NotFound.
+ _, err = client.Get(ctx, "no-such-sandbox")
+ require.True(t, IsRemoteNotFound(err))
+}
+
+func TestE2BRemoteClientGetResumesPausedSandbox(t *testing.T) {
+ mock := newE2BMockServer(t)
+ client := newTestE2BRemoteClient(t, mock)
+ handle, err := client.Create(context.Background(), RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+ mock.sandboxes[handle.ID()]["state"] = "paused"
+
+ summary, err := client.Get(context.Background(), handle.ID())
+ require.NoError(t, err)
+ require.Equal(t, handle.ID(), summary.ID)
+ // Get reattaches via Connect, which wakes the paused sandbox, so the
+ // subsequent info read reports it running. This is intended: Get's only
+ // caller connects (and therefore wakes) the sandbox immediately after.
+ require.Equal(t, RemoteStateRunning, summary.State)
+ require.Equal(t, int32(1), mock.connectCount.Load())
+ require.Zero(t, mock.v2ListCount.Load(), "Get must not scan the V2 sandbox list")
+}
+
+func TestE2BRemoteClientListTraversesAllV2Pages(t *testing.T) {
+ mock := newE2BMockServer(t)
+ for index := 0; index < 101; index++ {
+ id := fmt.Sprintf("sandbox-%03d", index)
+ mock.sandboxes[id] = map[string]any{
+ "sandboxID": id,
+ "templateID": "template-a",
+ "state": "running",
+ "startedAt": time.Now().UTC().Format(time.RFC3339),
+ }
+ }
+ client := newTestE2BRemoteClient(t, mock)
+
+ summaries, err := client.List(context.Background(), RemoteListFilter{})
+ require.NoError(t, err)
+ require.Len(t, summaries, 101)
+ require.Equal(t, int32(2), mock.v2ListCount.Load())
+
+ // Get is a direct by-ID lookup (Connect+info); it never touches the list.
+ mock.v2ListCount.Store(0)
+ summary, err := client.Get(context.Background(), "sandbox-100")
+ require.NoError(t, err)
+ require.Equal(t, "sandbox-100", summary.ID)
+ require.Zero(t, mock.v2ListCount.Load(), "Get must not scan the V2 sandbox list")
+ require.Equal(t, int32(1), mock.connectCount.Load())
+ require.Equal(t, int32(1), mock.infoCount.Load())
+}
+
+func TestE2BRemoteClientListRejectsRepeatedV2NextToken(t *testing.T) {
+ mock := newE2BMockServer(t)
+ mock.repeatV2NextToken = true
+ mock.sandboxes["sandbox-1"] = map[string]any{
+ "sandboxID": "sandbox-1",
+ "templateID": "template-a",
+ "state": "running",
+ "startedAt": time.Now().UTC().Format(time.RFC3339),
+ }
+ client := newTestE2BRemoteClient(t, mock)
+
+ _, err := client.List(context.Background(), RemoteListFilter{})
+ require.Error(t, err)
+ var remoteErr *RemoteError
+ require.ErrorAs(t, err, &remoteErr)
+ require.Equal(t, RemoteErrorKindInternal, remoteErr.Kind)
+ require.Equal(t, "List", remoteErr.Op)
+ require.Equal(t, int32(2), mock.v2ListCount.Load())
+}
+
+func TestE2BRemoteClientListRejectsUnsafeV2NextTokenBeforeNextRequest(t *testing.T) {
+ mock := newE2BMockServer(t)
+ mock.unsafeV2NextToken = "next&token"
+ mock.sandboxes["sandbox-1"] = map[string]any{
+ "sandboxID": "sandbox-1",
+ "state": "running",
+ }
+ client := newTestE2BRemoteClient(t, mock)
+
+ _, err := client.List(context.Background(), RemoteListFilter{})
+ require.Error(t, err)
+ var remoteErr *RemoteError
+ require.ErrorAs(t, err, &remoteErr)
+ require.Equal(t, RemoteErrorKindInternal, remoteErr.Kind)
+ require.Equal(t, "List", remoteErr.Op)
+ require.Contains(t, remoteErr.Error(), "unsafe")
+ require.Equal(t, int32(1), mock.v2ListCount.Load())
+}
+
+func TestE2BRemoteClientDeleteAcrossClients(t *testing.T) {
+ mock := newE2BMockServer(t)
+ creator := newTestE2BRemoteClient(t, mock)
+ ctx := context.Background()
+
+ handle, err := creator.Create(ctx, RemoteCreateRequest{TemplateID: "template-a"})
+ require.NoError(t, err)
+ deleter := newTestE2BRemoteClient(t, mock)
+ require.NoError(t, deleter.Delete(ctx, handle.ID()))
+ require.Equal(t, handle.ID(), mock.connectID)
+ require.Equal(t, int32(1), mock.connectCount.Load())
+ require.Equal(t, handle.ID(), mock.deleteID)
+ require.Equal(t, int32(1), mock.deleteCount.Load())
+
+ err = deleter.Delete(ctx, handle.ID())
+ require.True(t, IsRemoteNotFound(err))
+ require.Equal(t, int32(1), mock.deleteCount.Load())
+}
+
+func TestE2BRemoteClientFilesystemOperationsRejectEmptyPaths(t *testing.T) {
+ client := newTestE2BRemoteClient(t, newE2BMockServer(t))
+ handle := &e2bRemoteHandle{sandbox: &e2b.Sandbox{ID: "e2b-1"}}
+
+ _, err := client.ListDir(context.Background(), handle, " ")
+ require.True(t, IsRemoteInvalidRequest(err))
+ err = client.MakeDir(context.Background(), handle, " ")
+ require.True(t, IsRemoteInvalidRequest(err))
+ err = client.Remove(context.Background(), handle, " ")
+ require.True(t, IsRemoteInvalidRequest(err))
+ _, err = client.Stat(context.Background(), handle, " ")
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestE2BRemoteClientRejectsForeignHandle(t *testing.T) {
+ client := newTestE2BRemoteClient(t, newE2BMockServer(t))
+ _, err := client.ReadFile(
+ context.Background(),
+ &contractHandle{id: "cube-1", provider: SandboxTypeCube},
+ "/workspace/file",
+ )
+ require.True(t, IsRemoteInvalidRequest(err))
+}
+
+func TestNormalizeE2BState(t *testing.T) {
+ tests := map[string]RemoteSandboxState{
+ "": RemoteStateUnknown,
+ "running": RemoteStateRunning,
+ "paused": RemoteStatePaused,
+ "pausing": RemoteStateTransitioning,
+ "resuming": RemoteStateTransitioning,
+ "pending": RemoteStateTransitioning,
+ "killed": RemoteStateTerminal,
+ "terminated": RemoteStateTerminal,
+ "deleted": RemoteStateTerminal,
+ "failed": RemoteStateTerminal,
+ "stopped": RemoteStateTerminal,
+ "error": RemoteStateTerminal,
+ "weird-state": RemoteStateUnknown,
+ }
+ for raw, want := range tests {
+ require.Equalf(t, want, normalizeE2BState(raw), "state %q", raw)
+ }
+}
+
+func TestNormalizeE2BError(t *testing.T) {
+ tests := []struct {
+ name string
+ op string
+ err error
+ kind RemoteErrorKind
+ }{
+ {"sandbox not found", "Get", &e2b.SandboxNotFoundError{SandboxID: "e2b-1"}, RemoteErrorKindNotFound},
+ {"file not found", "ReadFile", &e2b.FileNotFoundError{Path: "/x"}, RemoteErrorKindNotFound},
+ {"template not found", "Create", &e2b.TemplateNotFoundError{TemplateID: "t"}, RemoteErrorKindInvalidRequest},
+ {"unauthorized", "Health", &e2b.Error{StatusCode: http.StatusUnauthorized}, RemoteErrorKindAuthentication},
+ {"rate limited", "Create", &e2b.Error{StatusCode: http.StatusTooManyRequests}, RemoteErrorKindCapacity},
+ {"gone", "Get", &e2b.Error{StatusCode: http.StatusGone}, RemoteErrorKindTerminal},
+ {"unavailable", "List", &e2b.Error{StatusCode: http.StatusBadGateway}, RemoteErrorKindUnavailable},
+ {"deadline", "Exec", context.DeadlineExceeded, RemoteErrorKindTimeout},
+ {"network timeout", "List", e2bTestNetError{timeout: true}, RemoteErrorKindTimeout},
+ {"network unavailable", "List", e2bTestNetError{}, RemoteErrorKindUnavailable},
+ {"connect canceled", "List", connect.NewError(connect.CodeCanceled, errors.New("canceled")), RemoteErrorKindTimeout},
+ {"connect deadline", "List", connect.NewError(connect.CodeDeadlineExceeded, errors.New("deadline")), RemoteErrorKindTimeout},
+ {"connect unavailable", "List", connect.NewError(connect.CodeUnavailable, errors.New("unavailable")), RemoteErrorKindUnavailable},
+ {"connect unauthenticated", "List", connect.NewError(connect.CodeUnauthenticated, errors.New("unauthenticated")), RemoteErrorKindAuthentication},
+ {"connect permission denied", "List", connect.NewError(connect.CodePermissionDenied, errors.New("permission denied")), RemoteErrorKindAuthentication},
+ {"connect resource exhausted", "List", connect.NewError(connect.CodeResourceExhausted, errors.New("resource exhausted")), RemoteErrorKindCapacity},
+ {"connect invalid argument", "List", connect.NewError(connect.CodeInvalidArgument, errors.New("invalid argument")), RemoteErrorKindInvalidRequest},
+ {"connect out of range", "List", connect.NewError(connect.CodeOutOfRange, errors.New("out of range")), RemoteErrorKindInvalidRequest},
+ {"connect not found", "List", connect.NewError(connect.CodeNotFound, errors.New("not found")), RemoteErrorKindNotFound},
+ {"connect already exists", "List", connect.NewError(connect.CodeAlreadyExists, errors.New("already exists")), RemoteErrorKindConflict},
+ {"connect aborted", "List", connect.NewError(connect.CodeAborted, errors.New("aborted")), RemoteErrorKindConflict},
+ {"connect failed precondition", "List", connect.NewError(connect.CodeFailedPrecondition, errors.New("failed precondition")), RemoteErrorKindConflict},
+ {"connect unimplemented", "List", connect.NewError(connect.CodeUnimplemented, errors.New("unimplemented")), RemoteErrorKindUnsupported},
+ {"connect internal", "List", connect.NewError(connect.CodeInternal, errors.New("internal")), RemoteErrorKindInternal},
+ {"connect data loss", "List", connect.NewError(connect.CodeDataLoss, errors.New("data loss")), RemoteErrorKindInternal},
+ {"connect unknown", "List", connect.NewError(connect.CodeUnknown, errors.New("unknown")), RemoteErrorKindInternal},
+ {"unknown", "List", errors.New("mystery"), RemoteErrorKindInternal},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := normalizeE2BError(tt.op, tt.err)
+ var remoteErr *RemoteError
+ require.ErrorAs(t, err, &remoteErr)
+ require.Equal(t, tt.kind, remoteErr.Kind)
+ require.Equal(t, SandboxTypeE2B, remoteErr.Provider)
+ require.ErrorIs(t, err, tt.err)
+ })
+ }
+
+ t.Run("context canceled remains discoverable", func(t *testing.T) {
+ err := normalizeE2BError("List", fmt.Errorf("wrapped: %w", context.Canceled))
+ require.ErrorIs(t, err, context.Canceled)
+ })
+}
diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go
index afd330e68..d9aa533d0 100644
--- a/internal/sandbox/manager.go
+++ b/internal/sandbox/manager.go
@@ -74,6 +74,17 @@ func (m *DefaultManager) initializeSandbox(ctx context.Context) error {
m.sandbox = NewLocalSandbox(m.config)
return nil
+ case SandboxTypeCube, SandboxTypeE2B:
+ // Session-scoped remote backends are only reachable through
+ // SessionBoundManager, which owns the authoritative binding.
+ // DefaultManager exposes stateless semantics that cannot preserve
+ // per-session state, so we refuse the construction and let
+ // NewManagerFromType route the caller to NewSessionBoundManager.
+ return fmt.Errorf(
+ "sandbox: %s backend must be constructed via NewSessionBoundManager",
+ m.config.Type,
+ )
+
default:
return fmt.Errorf("unknown sandbox type: %s", m.config.Type)
}
@@ -97,7 +108,7 @@ func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*E
// Perform security validation unless explicitly skipped
if !config.SkipValidation {
- if err := m.validateExecution(config); err != nil {
+ if err := runScriptValidation(m.validator, config); err != nil {
log.Printf("[sandbox] Security validation failed: %v", err)
return &ExecuteResult{
ExitCode: -1,
@@ -110,9 +121,13 @@ func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*E
return sandbox.Execute(ctx, config)
}
-// validateExecution performs comprehensive security validation on the execution config
-func (m *DefaultManager) validateExecution(config *ExecuteConfig) error {
- if m.validator == nil {
+// runScriptValidation is the package-level helper that DefaultManager and
+// SessionBoundManager share for pre-execution security checks. Extracting
+// it avoids duplicating the same script/args/stdin validation logic across
+// two Manager implementations while keeping the ScriptValidator private to
+// the manager that owns it.
+func runScriptValidation(validator *ScriptValidator, config *ExecuteConfig) error {
+ if validator == nil || config == nil {
return nil
}
@@ -128,13 +143,11 @@ func (m *DefaultManager) validateExecution(config *ExecuteConfig) error {
// Validate script content
if scriptContent != "" {
- result := m.validator.ValidateScript(scriptContent)
+ result := validator.ValidateScript(scriptContent)
if !result.Valid {
- // Log all validation errors
for _, verr := range result.Errors {
log.Printf("[sandbox] Validation error: %s", verr.Error())
}
- // Return the first error
if len(result.Errors) > 0 {
return result.Errors[0]
}
@@ -144,7 +157,7 @@ func (m *DefaultManager) validateExecution(config *ExecuteConfig) error {
// Validate arguments
if len(config.Args) > 0 {
- result := m.validator.ValidateArgs(config.Args)
+ result := validator.ValidateArgs(config.Args)
if !result.Valid {
for _, verr := range result.Errors {
log.Printf("[sandbox] Arg validation error: %s", verr.Error())
@@ -158,7 +171,7 @@ func (m *DefaultManager) validateExecution(config *ExecuteConfig) error {
// Validate stdin
if config.Stdin != "" {
- result := m.validator.ValidateStdin(config.Stdin)
+ result := validator.ValidateStdin(config.Stdin)
if !result.Valid {
for _, verr := range result.Errors {
log.Printf("[sandbox] Stdin validation error: %s", verr.Error())
@@ -224,6 +237,10 @@ 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.
func NewManagerFromType(sandboxType string, fallbackEnabled bool, dockerImage string) (Manager, error) {
var sType SandboxType
switch sandboxType {
@@ -231,6 +248,10 @@ func NewManagerFromType(sandboxType string, fallbackEnabled bool, dockerImage st
sType = SandboxTypeDocker
case "local":
sType = SandboxTypeLocal
+ case "cube":
+ sType = SandboxTypeCube
+ case "e2b":
+ sType = SandboxTypeE2B
case "disabled", "":
sType = SandboxTypeDisabled
default:
@@ -244,6 +265,30 @@ func NewManagerFromType(sandboxType string, fallbackEnabled bool, dockerImage st
config.DockerImage = dockerImage
}
+ switch sType {
+ case SandboxTypeCube:
+ client, err := NewCubeRemoteClient(config)
+ if 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 {
+ return nil, fmt.Errorf("sandbox: build E2B client: %w", err)
+ }
+ return NewSessionBoundManager(SessionBoundManagerConfig{
+ Config: config,
+ Client: client,
+ Store: NewMemorySessionSandboxBindingStore(),
+ Checker: PermissiveSessionExistenceChecker{},
+ })
+ }
return NewManager(config)
}
diff --git a/internal/sandbox/orphan_reaper.go b/internal/sandbox/orphan_reaper.go
new file mode 100644
index 000000000..b6dfc5d50
--- /dev/null
+++ b/internal/sandbox/orphan_reaper.go
@@ -0,0 +1,90 @@
+// Package sandbox: orphan sandbox reconciliation.
+//
+// Session sandboxes are created with onTimeout=pause + autoResume (see
+// buildSessionCreateRequest), so the provider TTL PAUSES them rather than
+// destroying them. When a binding is replaced — the CAS that happens when a
+// workspace switches provider — or lost (Redis TTL, process restart), the old
+// sandbox ID disappears from our records while the sandbox itself lingers in a
+// paused state, consuming snapshot storage and money.
+//
+// Neither existing cleanup path covers that: session deletion works from a
+// live binding, and the lifecycle's orphan cleanup is lazy, triggering only
+// when someone touches the binding that has already been overwritten.
+//
+// This reconciliation loop closes the gap by enumerating the provider's
+// sandboxes via the tenant metadata every sandbox is tagged with, comparing
+// against the authoritative bindings, and deleting what is unbound. Paused
+// sandboxes MUST be included: they are precisely the leaked ones.
+package sandbox
+
+import (
+ "context"
+ "fmt"
+ "time"
+)
+
+// orphanReaperClient is the narrow slice of RemoteSandboxClient the reaper
+// needs, declared separately so tests can supply a small fake.
+type orphanReaperClient interface {
+ List(ctx context.Context, filter RemoteListFilter) ([]RemoteSandboxSummary, error)
+ Delete(ctx context.Context, sandboxID string) error
+}
+
+// OrphanReaperDeps configures one reconciliation pass for a single tenant.
+type OrphanReaperDeps struct {
+ Client orphanReaperClient
+
+ // BoundIDs is the set of sandbox IDs the binding store still considers
+ // owned. Anything outside this set is a deletion candidate.
+ BoundIDs map[string]struct{}
+
+ TenantID uint64
+
+ // ConfigID scopes the sweep to one sandbox config. Empty means the
+ // deployment default config. Sweeping by tenant alone would delete
+ // sandboxes belonging to a sibling config on the same provider account.
+ ConfigID string
+
+ // Grace protects freshly created sandboxes that may not be bound yet.
+ // Pass 0 when reaping deliberately (e.g. before a backend switch), where
+ // every sandbox on the old backend is known to be abandoned.
+ Grace time.Duration
+
+ Now func() time.Time
+}
+
+// ReapOrphanSandboxes deletes unbound sandboxes for one tenant and reports how
+// many were removed.
+func ReapOrphanSandboxes(ctx context.Context, deps OrphanReaperDeps) (int, error) {
+ if deps.Client == nil {
+ return 0, fmt.Errorf("sandbox: orphan reaper requires a client")
+ }
+ now := deps.Now
+ if now == nil {
+ now = time.Now
+ }
+
+ summaries, err := deps.Client.List(ctx, configSandboxFilter(deps.TenantID, deps.ConfigID))
+ if err != nil {
+ return 0, fmt.Errorf(
+ "sandbox: list workspace %d config %q sandboxes: %w",
+ deps.TenantID, NormalizeConfigID(deps.ConfigID), err)
+ }
+
+ cutoff := now().Add(-deps.Grace)
+ deleted := 0
+ for _, summary := range summaries {
+ if _, bound := deps.BoundIDs[summary.ID]; bound {
+ continue
+ }
+ if deps.Grace > 0 && !summary.StartedAt.IsZero() && summary.StartedAt.After(cutoff) {
+ continue
+ }
+ if err := deps.Client.Delete(ctx, summary.ID); err != nil {
+ // Keep going: one undeletable sandbox must not abort the sweep.
+ continue
+ }
+ deleted++
+ }
+ return deleted, nil
+}
diff --git a/internal/sandbox/orphan_reaper_test.go b/internal/sandbox/orphan_reaper_test.go
new file mode 100644
index 000000000..ca30a26e8
--- /dev/null
+++ b/internal/sandbox/orphan_reaper_test.go
@@ -0,0 +1,113 @@
+package sandbox
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+type fakeReaperClient struct {
+ summaries []RemoteSandboxSummary
+ states []RemoteSandboxState
+ deleted []string
+}
+
+func (f *fakeReaperClient) List(
+ _ context.Context, filter RemoteListFilter,
+) ([]RemoteSandboxSummary, error) {
+ f.states = filter.States
+ return f.summaries, nil
+}
+
+func (f *fakeReaperClient) Delete(_ context.Context, id string) error {
+ f.deleted = append(f.deleted, id)
+ return nil
+}
+
+// Paused sandboxes are the whole point: onTimeout=pause means the provider TTL
+// never reclaims them, so a sweep that only looked at running ones would miss
+// every leaked instance.
+func TestReapOrphanSandboxesDeletesUnboundIncludingPaused(t *testing.T) {
+ now := time.Now()
+ client := &fakeReaperClient{summaries: []RemoteSandboxSummary{
+ {ID: "sbx-bound", State: RemoteStateRunning, StartedAt: now.Add(-2 * time.Hour)},
+ {ID: "sbx-orphan-running", State: RemoteStateRunning, StartedAt: now.Add(-2 * time.Hour)},
+ {ID: "sbx-orphan-paused", State: RemoteStatePaused, StartedAt: now.Add(-2 * time.Hour)},
+ // Inside the grace window: may still be mid-creation and unbound.
+ {ID: "sbx-fresh", State: RemoteStateRunning, StartedAt: now.Add(-1 * time.Minute)},
+ }}
+
+ deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
+ Client: client,
+ BoundIDs: map[string]struct{}{"sbx-bound": {}},
+ TenantID: 7,
+ Grace: 30 * time.Minute,
+ Now: func() time.Time { return now },
+ })
+
+ require.NoError(t, err)
+ require.Equal(t, 2, deleted)
+ require.ElementsMatch(t,
+ []string{"sbx-orphan-running", "sbx-orphan-paused"}, client.deleted)
+ require.Contains(t, client.states, RemoteStatePaused,
+ "the listing filter must include paused sandboxes")
+}
+
+func TestReapOrphanSandboxesKeepsBoundSandboxes(t *testing.T) {
+ now := time.Now()
+ client := &fakeReaperClient{summaries: []RemoteSandboxSummary{
+ {ID: "sbx-a", State: RemoteStatePaused, StartedAt: now.Add(-5 * time.Hour)},
+ }}
+
+ deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
+ Client: client,
+ BoundIDs: map[string]struct{}{"sbx-a": {}},
+ TenantID: 7,
+ Grace: time.Minute,
+ Now: func() time.Time { return now },
+ })
+
+ require.NoError(t, err)
+ require.Zero(t, deleted)
+ require.Empty(t, client.deleted)
+}
+
+// Grace=0 is the backend-switch case: everything on the old backend is known to
+// be abandoned, so even a just-created sandbox must be reaped.
+func TestReapOrphanSandboxesZeroGraceIgnoresAge(t *testing.T) {
+ now := time.Now()
+ client := &fakeReaperClient{summaries: []RemoteSandboxSummary{
+ {ID: "sbx-fresh", State: RemoteStateRunning, StartedAt: now},
+ }}
+
+ deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
+ Client: client,
+ TenantID: 7,
+ Grace: 0,
+ Now: func() time.Time { return now },
+ })
+
+ require.NoError(t, err)
+ require.Equal(t, 1, deleted)
+}
+
+// The reaper must not reach across configs, even when both live on the same
+// provider account.
+func TestReapOrphanSandboxesScopesToConfig(t *testing.T) {
+ client := &fakeConfigSandboxClient{inventory: []RemoteSandboxSummary{
+ summary("sb-a", "7", "cfg-a"),
+ summary("sb-b", "7", "cfg-b"),
+ }}
+
+ deleted, err := ReapOrphanSandboxes(context.Background(), OrphanReaperDeps{
+ Client: client,
+ TenantID: 7,
+ ConfigID: "cfg-a",
+ BoundIDs: map[string]struct{}{},
+ })
+ require.NoError(t, err)
+ require.Equal(t, 1, deleted)
+ require.Equal(t, []string{"sb-a"}, client.deleted)
+}
diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.go
new file mode 100644
index 000000000..5fdee0bb3
--- /dev/null
+++ b/internal/sandbox/remote_client.go
@@ -0,0 +1,416 @@
+// Package sandbox: provider-neutral remote sandbox contract.
+//
+// This file introduces the RemoteSandboxClient interface and the neutral
+// data-transfer types that SessionBoundManager depends on. Concrete backends
+// (Cube, E2B) each provide an implementation
+// in a separate adapter file.
+//
+// The interface is deliberately minimal: it covers only the operations
+// SessionBoundManager and RemoteSandbox use in production today. Optional
+// provider capabilities (pause/resume, timeout refresh, metadata recovery,
+// etc.) are exposed as RemoteSandboxCapabilities so higher layers can degrade
+// gracefully instead of relying on backend-specific type assertions.
+package sandbox
+
+import (
+ "context"
+ "time"
+)
+
+// RemoteProvider identifies a remote sandbox backend. Values match the
+// user-facing WEKNORA_SANDBOX_MODE strings and the existing SandboxType
+// aliases so wiring/logging stays uniform.
+type RemoteProvider = SandboxType
+
+// RemoteSandboxHandle is an opaque, provider-issued reference to a live
+// sandbox. Adapters may wrap their SDK-specific object (e.g.
+// *cubesandbox.Sandbox, *e2b.Sandbox) inside the concrete handle type; the
+// manager only reads the stable identifiers exposed here.
+type RemoteSandboxHandle interface {
+ // ID returns the provider-scoped sandbox identifier.
+ ID() string
+
+ // Provider returns the backend that issued this handle.
+ Provider() RemoteProvider
+
+ // Metadata returns the metadata originally recorded with the sandbox on
+ // creation, when the provider preserves it. Returns nil when the provider
+ // does not support metadata recovery.
+ Metadata() map[string]string
+}
+
+// RemoteTimeoutMode describes how the remote provider should treat the
+// requested idle timeout.
+type RemoteTimeoutMode string
+
+const (
+ // RemoteTimeoutServerDefault leaves the timeout unspecified so the
+ // provider applies its configured default.
+ RemoteTimeoutServerDefault RemoteTimeoutMode = "server"
+
+ // RemoteTimeoutExplicit uses RemoteTimeoutPolicy.Value verbatim. A zero
+ // value asks for immediate on-timeout action; a negative value asks for
+ // "never" when the provider supports it (adapters return
+ // RemoteErrorKindUnsupported otherwise).
+ RemoteTimeoutExplicit RemoteTimeoutMode = "explicit"
+)
+
+// RemoteTimeoutAction is the provider-side action taken when idle timeout
+// elapses.
+type RemoteTimeoutAction string
+
+const (
+ // RemoteOnTimeoutPause pauses the sandbox and preserves its filesystem
+ // state so it can be resumed later.
+ RemoteOnTimeoutPause RemoteTimeoutAction = "pause"
+
+ // RemoteOnTimeoutKill destroys the sandbox and releases all resources.
+ RemoteOnTimeoutKill RemoteTimeoutAction = "kill"
+)
+
+// RemoteTimeoutPolicy is the provider-neutral timeout configuration.
+type RemoteTimeoutPolicy struct {
+ Mode RemoteTimeoutMode
+ Value time.Duration
+ Action RemoteTimeoutAction
+ // AutoResume asks the provider to resume a paused sandbox on the next
+ // Connect. Adapters that cannot honour this must return
+ // RemoteErrorKindUnsupported at Create time.
+ AutoResume bool
+}
+
+// RemoteVolumeMount describes a volume to mount into the sandbox at creation
+// time. Both Cube and E2B support named-volume mounts, making this a
+// provider-neutral concept. Each entry references a pre-created volume by
+// Name and the sandbox-internal Path at which it should appear.
+type RemoteVolumeMount struct {
+ // Name identifies the volume. Required.
+ Name string
+
+ // Path is the mount point inside the sandbox. Required.
+ Path string
+}
+
+// RemoteCreateRequest holds the neutral parameters for spawning a new sandbox.
+type RemoteCreateRequest struct {
+ // TemplateID references the pre-baked sandbox template. Required.
+ TemplateID string
+
+ // Timeout controls the idle-timeout policy.
+ Timeout RemoteTimeoutPolicy
+
+ // Metadata is a small key/value bag the provider stores alongside the
+ // sandbox. WeKnora uses this to recover ownership of stray sandboxes
+ // after a restart. Adapters that cannot persist metadata return
+ // RemoteErrorKindUnsupported when non-empty metadata is supplied.
+ Metadata map[string]string
+
+ // EnvVars is baked into the sandbox at creation time. Optional.
+ EnvVars map[string]string
+
+ // Network is the neutral outbound-network policy for the new sandbox.
+ // A zero-value policy asks the adapter to apply the provider's default
+ // behaviour (see RemoteNetworkPolicy for the exact semantics).
+ Network RemoteNetworkPolicy
+
+ // VolumeMounts specifies volumes to mount into the sandbox at creation
+ // time. Optional. When non-empty, the adapter maps each entry to the
+ // provider-native volume mount API (e2b.VolumeMount for E2B, etc.).
+ VolumeMounts []RemoteVolumeMount
+}
+
+// RemoteNetworkPolicy is the provider-neutral outbound-network policy for a
+// new sandbox. Only the fields both Cube and E2B accept live here; provider-
+// specific extensions (E2B request rules, Cube L7 policy, egress proxies,
+// masked host names) stay inside the adapters until we have a second caller
+// that needs them expressed at this layer.
+//
+// Field semantics match the underlying providers:
+//
+// - AllowInternetAccess: top-level egress switch. When nil the adapter
+// leaves it unset so the provider server-side default (typically true)
+// applies. When *false the sandbox has no default egress; specific
+// hosts must appear in AllowOut.
+// - AllowPublicTraffic: whether the sandbox is reachable from the public
+// internet by URL. nil defers to the provider default; false hides the
+// sandbox behind a per-sandbox traffic access token.
+// - AllowOut / DenyOut: CIDR blocks or domain names. Cube treats these as
+// L3/L4 filters; E2B applies domain-level filtering only on HTTP(S).
+// Both providers require that specific domain allow-lists be paired
+// with a deny-all (DenyOut: ["0.0.0.0/0"]) — the adapters surface the
+// provider-native error unchanged so callers can react.
+type RemoteNetworkPolicy struct {
+ AllowInternetAccess *bool
+ AllowPublicTraffic *bool
+ AllowOut []string
+ DenyOut []string
+}
+
+// IsZero reports whether the policy carries no caller-specified fields, in
+// which case adapters apply their own permissive defaults for backwards
+// compatibility with WeKnora deployments that predate provider-neutral
+// network policy.
+func (p RemoteNetworkPolicy) IsZero() bool {
+ return p.AllowInternetAccess == nil &&
+ p.AllowPublicTraffic == nil &&
+ len(p.AllowOut) == 0 &&
+ len(p.DenyOut) == 0
+}
+
+// RemoteSandboxSummary is the neutral view of a sandbox listing / probe.
+type RemoteSandboxSummary struct {
+ // ID is the provider-scoped sandbox identifier.
+ ID string
+
+ // TemplateID is the template the sandbox was created from.
+ TemplateID string
+
+ // State is the normalized lifecycle state. See RemoteSandboxState.
+ State RemoteSandboxState
+
+ // RawState is the provider-native state string, retained for diagnostics
+ // only. SessionBoundManager must not branch on RawState.
+ RawState string
+
+ // Metadata is the sandbox metadata bag. May be nil when the provider does
+ // not support metadata.
+ Metadata map[string]string
+
+ // StartedAt records when the sandbox was created; zero value when the
+ // provider does not report it.
+ StartedAt time.Time
+
+ // EndAt records when the sandbox was terminated; zero when unknown or
+ // still running.
+ EndAt time.Time
+}
+
+// RemoteSandboxState is the coordinator-facing lifecycle state.
+type RemoteSandboxState string
+
+const (
+ // RemoteStateRunning: sandbox is up and reachable.
+ RemoteStateRunning RemoteSandboxState = "running"
+
+ // RemoteStatePaused: sandbox is paused; resumable.
+ RemoteStatePaused RemoteSandboxState = "paused"
+
+ // RemoteStateTransitioning: sandbox is in a transient lifecycle state
+ // (pausing, resuming, provisioning, ...). Treated as "still owned" by
+ // SessionBoundManager but not immediately usable.
+ RemoteStateTransitioning RemoteSandboxState = "transitioning"
+
+ // RemoteStateTerminal: sandbox is gone. Bindings referencing this state
+ // can be replaced.
+ RemoteStateTerminal RemoteSandboxState = "terminal"
+
+ // RemoteStateUnknown: adapter could not classify the raw state. Treated
+ // as transient (do not replace the binding).
+ RemoteStateUnknown RemoteSandboxState = "unknown"
+)
+
+// RemoteListFilter narrows a List call. Empty fields mean "no filter".
+type RemoteListFilter struct {
+ // Metadata: only return sandboxes whose metadata contains all these
+ // key/value pairs. Adapters that cannot filter server-side may filter
+ // client-side and MUST return the same set.
+ Metadata map[string]string
+
+ // States restricts the response to the given normalized states. Empty
+ // means "any state".
+ States []RemoteSandboxState
+}
+
+// RemoteExecRequest describes a single command invocation. See the
+// RemoteSandboxClient.Exec contract for how Shell interacts with Args.
+type RemoteExecRequest struct {
+ // Command is the executable name (Shell=false) or the shell expression
+ // (Shell=true).
+ Command string
+
+ // Args are argv[1:] when Shell=false; must be empty when Shell=true.
+ Args []string
+
+ // Shell selects between direct exec (false) and shell interpretation
+ // (true). RemoteSandboxClient implementations must reject requests that
+ // combine Shell=true with a non-empty Args.
+ Shell bool
+
+ // Stdin is written to the process before it starts reading.
+ Stdin string
+
+ // Env is merged into the process environment.
+ Env map[string]string
+
+ // WorkDir is the process working directory. Empty means "provider
+ // default".
+ WorkDir string
+
+ // User is the OS user the process runs as. Empty means "provider
+ // default". Both backends support selecting it (E2B WithUser, Cube
+ // CommandOptions.User).
+ //
+ // Callers that rely on filesystem permissions for isolation MUST set a
+ // non-root user: root bypasses mode bits entirely, which would defeat
+ // read-only protection on shared volumes.
+ User string
+
+ // Timeout bounds a single exec call. Zero means "use provider default".
+ Timeout time.Duration
+}
+
+// DefaultSandboxExecUser is the non-root account WeKnora runs sandboxed
+// scripts as. The sandbox template must provision this user; E2B base
+// templates ship a "user" account, and Cube templates are expected to match.
+const DefaultSandboxExecUser = "user"
+
+// RemoteExecResult is the neutral shape returned by Exec.
+type RemoteExecResult struct {
+ Stdout string
+ Stderr string
+ ExitCode int
+ Duration time.Duration
+ Killed bool
+}
+
+// RemoteDirEntry describes one entry inside a directory listing.
+type RemoteDirEntry struct {
+ Name string
+ Path string
+ Type RemoteDirEntryType
+ Size int64
+ ModTime time.Time
+}
+
+// RemoteDirEntryType is the coordinator-facing entry kind.
+type RemoteDirEntryType string
+
+const (
+ RemoteEntryFile RemoteDirEntryType = "file"
+ RemoteEntryDir RemoteDirEntryType = "dir"
+ // RemoteEntryOther covers symlinks, sockets, devices, etc. WeKnora
+ // artifact code treats these as opaque and skips them.
+ RemoteEntryOther RemoteDirEntryType = "other"
+)
+
+// RemoteStatEntry is the neutral shape returned by Stat.
+type RemoteStatEntry struct {
+ Path string
+ Type RemoteDirEntryType
+ Size int64
+ ModTime time.Time
+}
+
+// RemoteSandboxCapabilities advertises which optional operations a client
+// supports natively. SessionBoundManager reads this to skip provider-specific
+// paths (e.g. metadata-based recovery) on backends that do not support them.
+//
+// Missing metadata/list capabilities use less-optimal but correct behaviour
+// (rely on the binding store instead of scanning provider metadata).
+// SupportsReconnect is required for persistent session lifecycle management.
+type RemoteSandboxCapabilities struct {
+ // SupportsReconnect is true when Connect can recover an operable handle
+ // from a provider-scoped sandbox ID after a WeKnora process restart.
+ SupportsReconnect bool
+
+ // SupportsMetadata is true when Create+List preserve the Metadata bag,
+ // enabling orphan-sandbox recovery after a WeKnora restart.
+ SupportsMetadata bool
+
+ // SupportsListSandboxes is true when List enumerates existing sandboxes
+ // (independent of metadata support).
+ SupportsListSandboxes bool
+
+ // SupportsPauseResume signals that idle sandboxes can be paused and
+ // resumed instead of destroyed. Purely informational for now; the
+ // current SessionBoundManager does not itself pause/resume.
+ SupportsPauseResume bool
+
+ // SupportsTimeoutRefresh indicates the provider can extend a sandbox's
+ // idle timeout after creation. Informational.
+ SupportsTimeoutRefresh bool
+
+ // SupportsFilesystemEnumeration is true when the provider implements
+ // ListDir, MakeDir, Stat, and Remove. SessionBoundManager only
+ // advertises the SessionFileStore capability when this is true — the
+ // application layer then knows to deregister list/read/attachment
+ // staging tools that would otherwise fail at request time.
+ SupportsFilesystemEnumeration bool
+
+ // SupportsVolumes is true when the provider can mount a named volume into
+ // a sandbox at creation time (RemoteCreateRequest.VolumeMounts). Callers
+ // use this to tell an operator up front that a backend cannot serve
+ // volume-based features, instead of failing later at first use.
+ SupportsVolumes bool
+}
+
+// RemoteSandboxClient is the contract SessionBoundManager talks to. All
+// backends (Cube, E2B, ...) must satisfy this interface via a thin adapter.
+//
+// Concurrency: implementations MUST be safe for concurrent use.
+//
+// Cancellation: every method must honour ctx.Done. Cancellation returns a
+// RemoteError whose Kind is RemoteErrorKindTimeout when the deadline elapsed
+// server-side, or the wrapped ctx.Err() otherwise.
+type RemoteSandboxClient interface {
+ // Provider identifies the backend. Used by the binding schema to detect
+ // provider mismatches after a mode switch.
+ Provider() RemoteProvider
+
+ // Capabilities returns the static capability set of this client. It is
+ // safe to call before Health succeeds.
+ Capabilities() RemoteSandboxCapabilities
+
+ // Health probes the provider's control plane. Returns nil when reachable.
+ Health(ctx context.Context) error
+
+ // --- lifecycle ---
+
+ // Create spawns a new sandbox and returns an opaque handle. The handle
+ // is owned by the caller; Delete must eventually be called.
+ Create(ctx context.Context, req RemoteCreateRequest) (RemoteSandboxHandle, error)
+
+ // Connect re-attaches to an already-running sandbox by ID. Adapters that
+ // cannot support reconnect must return RemoteErrorKindUnsupported here
+ // and set SupportsReconnect=false.
+ Connect(ctx context.Context, sandboxID string) (RemoteSandboxHandle, error)
+
+ // Get fetches a single sandbox summary by ID. Returns nil summary and
+ // RemoteErrorKindNotFound when the sandbox is gone.
+ Get(ctx context.Context, sandboxID string) (*RemoteSandboxSummary, error)
+
+ // List enumerates sandboxes visible to this client, optionally filtered.
+ List(ctx context.Context, filter RemoteListFilter) ([]RemoteSandboxSummary, error)
+
+ // Delete destroys a sandbox. Deleting a non-existent sandbox returns
+ // RemoteErrorKindNotFound; callers typically treat that as success.
+ Delete(ctx context.Context, sandboxID string) error
+
+ // --- execution ---
+
+ // Exec runs one command inside the sandbox. See RemoteExecRequest for
+ // the Shell/Args contract.
+ Exec(ctx context.Context, handle RemoteSandboxHandle, req RemoteExecRequest) (*RemoteExecResult, error)
+
+ // --- filesystem ---
+
+ WriteFile(ctx context.Context, handle RemoteSandboxHandle, path string, content []byte) error
+ ReadFile(ctx context.Context, handle RemoteSandboxHandle, path string) ([]byte, error)
+ ListDir(ctx context.Context, handle RemoteSandboxHandle, path string) ([]RemoteDirEntry, error)
+ MakeDir(ctx context.Context, handle RemoteSandboxHandle, path string) error
+ Remove(ctx context.Context, handle RemoteSandboxHandle, path string) error
+ Stat(ctx context.Context, handle RemoteSandboxHandle, path string) (*RemoteStatEntry, error)
+}
+
+// cloneMetadata returns a shallow copy of source. Nil input returns nil so
+// callers can distinguish "explicitly empty" from "not set".
+func cloneMetadata(source map[string]string) map[string]string {
+ if source == nil {
+ return nil
+ }
+ result := make(map[string]string, len(source))
+ for key, value := range source {
+ result[key] = value
+ }
+ return result
+}
diff --git a/internal/sandbox/remote_client_test.go b/internal/sandbox/remote_client_test.go
new file mode 100644
index 000000000..11506cc35
--- /dev/null
+++ b/internal/sandbox/remote_client_test.go
@@ -0,0 +1,121 @@
+package sandbox
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+type contractHandle struct {
+ id string
+ provider RemoteProvider
+ metadata map[string]string
+}
+
+func (h *contractHandle) ID() string { return h.id }
+func (h *contractHandle) Provider() RemoteProvider { return h.provider }
+func (h *contractHandle) Metadata() map[string]string { return h.metadata }
+
+type contractClient struct {
+ provider RemoteProvider
+ capabilities RemoteSandboxCapabilities
+}
+
+func (c *contractClient) Provider() RemoteProvider { return c.provider }
+func (c *contractClient) Capabilities() RemoteSandboxCapabilities {
+ return c.capabilities
+}
+func (c *contractClient) Health(context.Context) error { return nil }
+func (c *contractClient) Create(_ context.Context, req RemoteCreateRequest) (RemoteSandboxHandle, error) {
+ return &contractHandle{id: "sandbox-1", provider: c.provider, metadata: req.Metadata}, nil
+}
+func (c *contractClient) Connect(context.Context, string) (RemoteSandboxHandle, error) {
+ return &contractHandle{id: "sandbox-1", provider: c.provider}, nil
+}
+func (c *contractClient) Get(context.Context, string) (*RemoteSandboxSummary, error) {
+ return &RemoteSandboxSummary{ID: "sandbox-1", State: RemoteStateRunning}, nil
+}
+func (c *contractClient) List(context.Context, RemoteListFilter) ([]RemoteSandboxSummary, error) {
+ return []RemoteSandboxSummary{{ID: "sandbox-1", State: RemoteStateRunning}}, nil
+}
+func (c *contractClient) Delete(context.Context, string) error { return nil }
+func (c *contractClient) Exec(
+ context.Context,
+ RemoteSandboxHandle,
+ RemoteExecRequest,
+) (*RemoteExecResult, error) {
+ return &RemoteExecResult{ExitCode: 0}, nil
+}
+func (c *contractClient) WriteFile(context.Context, RemoteSandboxHandle, string, []byte) error {
+ return nil
+}
+func (c *contractClient) ReadFile(context.Context, RemoteSandboxHandle, string) ([]byte, error) {
+ return []byte("content"), nil
+}
+func (c *contractClient) ListDir(context.Context, RemoteSandboxHandle, string) ([]RemoteDirEntry, error) {
+ return []RemoteDirEntry{{Name: "file", Type: RemoteEntryFile}}, nil
+}
+func (c *contractClient) MakeDir(context.Context, RemoteSandboxHandle, string) error {
+ return nil
+}
+func (c *contractClient) Remove(context.Context, RemoteSandboxHandle, string) error {
+ return nil
+}
+func (c *contractClient) Stat(context.Context, RemoteSandboxHandle, string) (*RemoteStatEntry, error) {
+ return &RemoteStatEntry{Path: "/workspace/file", Type: RemoteEntryFile}, nil
+}
+
+var _ RemoteSandboxClient = (*contractClient)(nil)
+
+func TestRemoteClientContractExposesProviderAndReconnectCapability(t *testing.T) {
+ t.Parallel()
+
+ client := &contractClient{
+ provider: SandboxTypeE2B,
+ capabilities: RemoteSandboxCapabilities{
+ SupportsReconnect: true,
+ },
+ }
+
+ if got := client.Provider(); got != SandboxTypeE2B {
+ t.Fatalf("Provider() = %q, want %q", got, SandboxTypeE2B)
+ }
+ if !client.Capabilities().SupportsReconnect {
+ t.Fatal("reconnect capability must be explicit")
+ }
+}
+
+func TestRemoteTypesRepresentProviderNeutralSemantics(t *testing.T) {
+ t.Parallel()
+
+ timeout := RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: 15 * time.Minute,
+ Action: RemoteOnTimeoutPause,
+ AutoResume: true,
+ }
+ if timeout.Mode != RemoteTimeoutExplicit || timeout.Action != RemoteOnTimeoutPause {
+ t.Fatalf("unexpected timeout policy: %+v", timeout)
+ }
+
+ direct := RemoteExecRequest{Command: "python3", Args: []string{"-V"}}
+ if direct.Shell || len(direct.Args) != 1 {
+ t.Fatalf("direct execution lost argv semantics: %+v", direct)
+ }
+
+ shell := RemoteExecRequest{Command: "printf '%s' ok", Shell: true}
+ if !shell.Shell || len(shell.Args) != 0 {
+ t.Fatalf("shell execution representation is ambiguous: %+v", shell)
+ }
+
+ states := []RemoteSandboxState{
+ RemoteStateRunning,
+ RemoteStatePaused,
+ RemoteStateTransitioning,
+ RemoteStateTerminal,
+ RemoteStateUnknown,
+ }
+ if got, want := len(states), 5; got != want {
+ t.Fatalf("normalized state count = %d, want %d", got, want)
+ }
+}
diff --git a/internal/sandbox/remote_errors.go b/internal/sandbox/remote_errors.go
new file mode 100644
index 000000000..ec251d02d
--- /dev/null
+++ b/internal/sandbox/remote_errors.go
@@ -0,0 +1,196 @@
+// Package sandbox: provider-neutral error contract for RemoteSandboxClient.
+//
+// Adapters normalize provider-native errors (HTTP status codes, SDK error
+// types, gRPC codes) into RemoteError with a stable Kind so SessionBoundManager
+// can make lifecycle decisions without knowing which backend is in use.
+//
+// Rule of thumb for adapters:
+//
+// - NotFound / Terminal → binding may be replaced
+// - Timeout / Unavailable / Capacity / Conflict / Authentication → PRESERVE binding
+// - InvalidRequest / Unsupported → surface to caller; do not touch binding
+// - Internal → last resort; preserve binding (default-preserve on ambiguity)
+//
+// The original cause is always retained via errors.Unwrap so callers can
+// still inspect provider-specific detail when logging.
+package sandbox
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+)
+
+// RemoteErrorKind is the stable, provider-neutral classification of a
+// RemoteSandboxClient failure.
+type RemoteErrorKind string
+
+const (
+ // RemoteErrorKindNotFound: sandbox / file / path does not exist.
+ RemoteErrorKindNotFound RemoteErrorKind = "not_found"
+
+ // RemoteErrorKindTerminal: sandbox is permanently gone (killed,
+ // crashed, terminated). Semantically equivalent to NotFound for
+ // lifecycle purposes but distinct for observability.
+ RemoteErrorKindTerminal RemoteErrorKind = "terminal"
+
+ // RemoteErrorKindAuthentication: bad credentials, expired token, etc.
+ RemoteErrorKindAuthentication RemoteErrorKind = "authentication"
+
+ // RemoteErrorKindInvalidRequest: caller-side error (bad template ID,
+ // bad path, oversized payload). Not retryable.
+ RemoteErrorKindInvalidRequest RemoteErrorKind = "invalid_request"
+
+ // RemoteErrorKindUnsupported: provider does not implement the requested
+ // capability (e.g. metadata, "never" timeout).
+ RemoteErrorKindUnsupported RemoteErrorKind = "unsupported"
+
+ // RemoteErrorKindConflict: concurrent modification (e.g. sandbox state
+ // changed under us, template being built).
+ RemoteErrorKindConflict RemoteErrorKind = "conflict"
+
+ // RemoteErrorKindCapacity: quota / rate-limit / out-of-capacity.
+ RemoteErrorKindCapacity RemoteErrorKind = "capacity"
+
+ // RemoteErrorKindTimeout: request exceeded its deadline before the
+ // provider responded. Distinct from execution timeout, which is a
+ // normal RemoteExecResult with Killed=true.
+ RemoteErrorKindTimeout RemoteErrorKind = "timeout"
+
+ // RemoteErrorKindUnavailable: transient provider outage (5xx, network
+ // error, control-plane unreachable).
+ RemoteErrorKindUnavailable RemoteErrorKind = "unavailable"
+
+ // RemoteErrorKindInternal: catch-all for unclassified failures.
+ // Adapters SHOULD narrow this to a more specific kind when possible.
+ RemoteErrorKindInternal RemoteErrorKind = "internal"
+)
+
+// RemoteError is the wire-agnostic error type returned by every
+// RemoteSandboxClient method.
+type RemoteError struct {
+ // Kind classifies the failure for coordinator decisions.
+ Kind RemoteErrorKind
+
+ // Provider identifies which backend produced the error, for logging.
+ Provider RemoteProvider
+
+ // Op names the RemoteSandboxClient operation (e.g. "Create", "Exec").
+ Op string
+
+ // Message is a human-readable summary. Provider-specific status codes
+ // or SDK error strings belong here.
+ Message string
+
+ // Cause is the original provider-side error, retained for
+ // errors.Unwrap so callers can still errors.Is / errors.As it.
+ Cause error
+}
+
+// Error implements the error interface.
+func (e *RemoteError) Error() string {
+ if e == nil {
+ return "<nil remote error>"
+ }
+ prov := string(e.Provider)
+ if prov == "" {
+ prov = "remote"
+ }
+ if e.Message == "" && e.Cause != nil {
+ return fmt.Sprintf("%s %s: %s: %v", prov, e.Op, e.Kind, e.Cause)
+ }
+ if e.Cause != nil {
+ return fmt.Sprintf("%s %s: %s: %s: %v", prov, e.Op, e.Kind, e.Message, e.Cause)
+ }
+ return fmt.Sprintf("%s %s: %s: %s", prov, e.Op, e.Kind, e.Message)
+}
+
+// Unwrap exposes the wrapped provider-native error for errors.Is / errors.As.
+func (e *RemoteError) Unwrap() error {
+ if e == nil {
+ return nil
+ }
+ return e.Cause
+}
+
+// NewRemoteError builds a RemoteError. Convenience for adapters.
+func NewRemoteError(provider RemoteProvider, op string, kind RemoteErrorKind, message string, cause error) *RemoteError {
+ return &RemoteError{
+ Kind: kind,
+ Provider: provider,
+ Op: op,
+ Message: message,
+ Cause: cause,
+ }
+}
+
+// remoteKind extracts the Kind from err, or "" when err is not a
+// *RemoteError. Wraps errors.As so callers can pass any error value.
+func remoteKind(err error) RemoteErrorKind {
+ if err == nil {
+ return ""
+ }
+ var re *RemoteError
+ if errors.As(err, &re) {
+ return re.Kind
+ }
+ return ""
+}
+
+// IsRemoteNotFound reports whether err classifies as sandbox / path not found.
+// Both NotFound and Terminal are treated as "gone" for coordinator decisions.
+func IsRemoteNotFound(err error) bool {
+ switch remoteKind(err) {
+ case RemoteErrorKindNotFound, RemoteErrorKindTerminal:
+ return true
+ default:
+ return false
+ }
+}
+
+// IsRemoteInvalidRequest reports whether err classifies as a caller-side
+// error (bad template, oversized payload, malformed path, etc.).
+func IsRemoteInvalidRequest(err error) bool {
+ return remoteKind(err) == RemoteErrorKindInvalidRequest
+}
+
+// CanReplaceRemoteBinding reports whether the error proves that the bound
+// remote sandbox is permanently gone. This is intentionally allow-list based:
+// unknown and newly introduced errors preserve bindings by default.
+func CanReplaceRemoteBinding(err error) bool {
+ switch remoteKind(err) {
+ case RemoteErrorKindNotFound, RemoteErrorKindTerminal:
+ return true
+ default:
+ return false
+ }
+}
+
+// httpErrorKind maps an HTTP status code to a RemoteErrorKind. It is shared
+// by all remote sandbox adapter backends (Cube, E2B).
+func httpErrorKind(op string, status int) RemoteErrorKind {
+ switch status {
+ case http.StatusBadRequest, http.StatusUnprocessableEntity:
+ return RemoteErrorKindInvalidRequest
+ case http.StatusUnauthorized, http.StatusForbidden:
+ return RemoteErrorKindAuthentication
+ case http.StatusNotFound:
+ if op == "Create" {
+ return RemoteErrorKindInvalidRequest
+ }
+ return RemoteErrorKindNotFound
+ case http.StatusRequestTimeout, http.StatusGatewayTimeout:
+ return RemoteErrorKindTimeout
+ case http.StatusConflict:
+ return RemoteErrorKindConflict
+ case http.StatusGone:
+ return RemoteErrorKindTerminal
+ case http.StatusTooManyRequests, http.StatusInsufficientStorage:
+ return RemoteErrorKindCapacity
+ default:
+ if status >= 500 {
+ return RemoteErrorKindUnavailable
+ }
+ return RemoteErrorKindInternal
+ }
+}
diff --git a/internal/sandbox/remote_errors_test.go b/internal/sandbox/remote_errors_test.go
new file mode 100644
index 000000000..355afd089
--- /dev/null
+++ b/internal/sandbox/remote_errors_test.go
@@ -0,0 +1,113 @@
+package sandbox
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+)
+
+func TestRemoteBindingDecision(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ err error
+ replace bool
+ preserve bool
+ }{
+ {name: "nil", err: nil},
+ {
+ name: "not found",
+ err: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindNotFound, "gone", nil),
+ replace: true,
+ preserve: false,
+ },
+ {
+ name: "terminal",
+ err: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindTerminal, "terminated", nil),
+ replace: true,
+ preserve: false,
+ },
+ {
+ name: "authentication",
+ err: NewRemoteError(SandboxTypeCube, "Connect", RemoteErrorKindAuthentication, "denied", nil),
+ preserve: true,
+ },
+ {
+ name: "invalid request",
+ err: NewRemoteError(SandboxTypeCube, "Create", RemoteErrorKindInvalidRequest, "bad template", nil),
+ preserve: true,
+ },
+ {
+ name: "unsupported",
+ err: NewRemoteError(SandboxTypeCube, "Connect", RemoteErrorKindUnsupported, "no reconnect", nil),
+ preserve: true,
+ },
+ {
+ name: "conflict",
+ err: NewRemoteError(SandboxTypeCube, "Delete", RemoteErrorKindConflict, "busy", nil),
+ preserve: true,
+ },
+ {
+ name: "capacity",
+ err: NewRemoteError(SandboxTypeCube, "Create", RemoteErrorKindCapacity, "full", nil),
+ preserve: true,
+ },
+ {
+ name: "timeout",
+ err: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindTimeout, "deadline", nil),
+ preserve: true,
+ },
+ {
+ name: "unavailable",
+ err: NewRemoteError(SandboxTypeCube, "Health", RemoteErrorKindUnavailable, "offline", nil),
+ preserve: true,
+ },
+ {
+ name: "internal",
+ err: NewRemoteError(SandboxTypeCube, "List", RemoteErrorKindInternal, "unknown", nil),
+ preserve: true,
+ },
+ {
+ name: "wrapped terminal",
+ err: fmt.Errorf("probe failed: %w", NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindTerminal, "dead", nil)),
+ replace: true,
+ preserve: false,
+ },
+ {
+ name: "unclassified defaults to preserve",
+ err: errors.New("provider returned an unknown error"),
+ preserve: true,
+ },
+ }
+
+ for _, tt := range tests {
+ tt := tt
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ if got := CanReplaceRemoteBinding(tt.err); got != tt.replace {
+ t.Fatalf("CanReplaceRemoteBinding() = %v, want %v", got, tt.replace)
+ }
+ })
+ }
+}
+
+func TestRemoteErrorRetainsCause(t *testing.T) {
+ t.Parallel()
+
+ cause := errors.New("connection reset")
+ err := NewRemoteError(
+ SandboxTypeCube,
+ "Connect",
+ RemoteErrorKindUnavailable,
+ "control plane unavailable",
+ cause,
+ )
+
+ if !errors.Is(err, cause) {
+ t.Fatal("RemoteError must retain its provider-native cause")
+ }
+ if got, want := err.Error(), "cube Connect: unavailable: control plane unavailable: connection reset"; got != want {
+ t.Fatalf("Error() = %q, want %q", got, want)
+ }
+}
diff --git a/internal/sandbox/remote_fake_test.go b/internal/sandbox/remote_fake_test.go
new file mode 100644
index 000000000..ed52fc72b
--- /dev/null
+++ b/internal/sandbox/remote_fake_test.go
@@ -0,0 +1,369 @@
+package sandbox
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "time"
+)
+
+type fakeRemoteHandle struct {
+ id string
+ provider RemoteProvider
+ metadata map[string]string
+}
+
+func (h *fakeRemoteHandle) ID() string { return h.id }
+func (h *fakeRemoteHandle) Provider() RemoteProvider { return h.provider }
+func (h *fakeRemoteHandle) Metadata() map[string]string {
+ return cloneStringMap(h.metadata)
+}
+
+type fakeRemoteRecord struct {
+ id string
+ templateID string
+ state RemoteSandboxState
+ rawState string
+ metadata map[string]string
+ startedAt time.Time
+}
+
+type fakeRemoteClient struct {
+ mu sync.Mutex
+ provider RemoteProvider
+ capabilities RemoteSandboxCapabilities
+ nextID int
+ sandboxes map[string]*fakeRemoteRecord
+
+ createCount int
+ connectIDs []string
+ getIDs []string
+ deleteIDs []string
+ listCount int
+
+ createErr error
+ connectErrs map[string]error
+ getErrs map[string]error
+ deleteErrs map[string]error
+ listErr error
+ createHook func(context.Context, RemoteCreateRequest) error
+ afterCreate func(RemoteSandboxHandle)
+ deleteHook func(context.Context, string) error
+
+ makeDirPaths []string
+ execRequests []RemoteExecRequest
+}
+
+func newFakeRemoteClient(provider RemoteProvider) *fakeRemoteClient {
+ return &fakeRemoteClient{
+ provider: provider,
+ capabilities: RemoteSandboxCapabilities{
+ SupportsReconnect: true,
+ SupportsMetadata: true,
+ SupportsListSandboxes: true,
+ SupportsFilesystemEnumeration: true,
+ },
+ sandboxes: make(map[string]*fakeRemoteRecord),
+ connectErrs: make(map[string]error),
+ getErrs: make(map[string]error),
+ deleteErrs: make(map[string]error),
+ }
+}
+
+func (c *fakeRemoteClient) Provider() RemoteProvider { return c.provider }
+
+func (c *fakeRemoteClient) Capabilities() RemoteSandboxCapabilities {
+ return c.capabilities
+}
+
+func (c *fakeRemoteClient) Health(context.Context) error { return nil }
+
+func (c *fakeRemoteClient) Create(
+ ctx context.Context,
+ req RemoteCreateRequest,
+) (RemoteSandboxHandle, error) {
+ c.mu.Lock()
+ c.createCount++
+ err := c.createErr
+ hook := c.createHook
+ c.mu.Unlock()
+
+ if err != nil {
+ return nil, err
+ }
+ if hook != nil {
+ if err := hook(ctx, req); err != nil {
+ return nil, err
+ }
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+
+ c.mu.Lock()
+ c.nextID++
+ id := fmt.Sprintf("%s-%d", c.provider, c.nextID)
+ record := &fakeRemoteRecord{
+ id: id,
+ templateID: req.TemplateID,
+ state: RemoteStateRunning,
+ rawState: string(RemoteStateRunning),
+ metadata: cloneStringMap(req.Metadata),
+ startedAt: time.Now().UTC(),
+ }
+ c.sandboxes[id] = record
+ handle := c.handle(record)
+ afterCreate := c.afterCreate
+ c.mu.Unlock()
+ if afterCreate != nil {
+ afterCreate(handle)
+ }
+ return handle, nil
+}
+
+func (c *fakeRemoteClient) Connect(
+ ctx context.Context,
+ sandboxID string,
+) (RemoteSandboxHandle, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.connectIDs = append(c.connectIDs, sandboxID)
+ if err := c.connectErrs[sandboxID]; err != nil {
+ return nil, err
+ }
+ record := c.sandboxes[sandboxID]
+ if record == nil || record.state == RemoteStateTerminal {
+ return nil, NewRemoteError(
+ c.provider,
+ "Connect",
+ RemoteErrorKindNotFound,
+ "sandbox not found",
+ nil,
+ )
+ }
+ return c.handle(record), nil
+}
+
+func (c *fakeRemoteClient) Get(
+ ctx context.Context,
+ sandboxID string,
+) (*RemoteSandboxSummary, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.getIDs = append(c.getIDs, sandboxID)
+ if err := c.getErrs[sandboxID]; err != nil {
+ return nil, err
+ }
+ record := c.sandboxes[sandboxID]
+ if record == nil {
+ return nil, NewRemoteError(
+ c.provider,
+ "Get",
+ RemoteErrorKindNotFound,
+ "sandbox not found",
+ nil,
+ )
+ }
+ return c.summary(record), nil
+}
+
+func (c *fakeRemoteClient) List(
+ ctx context.Context,
+ filter RemoteListFilter,
+) ([]RemoteSandboxSummary, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.listCount++
+ if c.listErr != nil {
+ return nil, c.listErr
+ }
+ result := make([]RemoteSandboxSummary, 0)
+ for _, record := range c.sandboxes {
+ if !metadataContains(record.metadata, filter.Metadata) ||
+ !stateMatches(record.state, filter.States) {
+ continue
+ }
+ result = append(result, *c.summary(record))
+ }
+ return result, nil
+}
+
+func (c *fakeRemoteClient) Delete(ctx context.Context, sandboxID string) error {
+ c.mu.Lock()
+ hook := c.deleteHook
+ c.mu.Unlock()
+ if hook != nil {
+ if err := hook(ctx, sandboxID); err != nil {
+ return err
+ }
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.deleteIDs = append(c.deleteIDs, sandboxID)
+ if err := c.deleteErrs[sandboxID]; err != nil {
+ return err
+ }
+ if _, ok := c.sandboxes[sandboxID]; !ok {
+ return NewRemoteError(
+ c.provider,
+ "Delete",
+ RemoteErrorKindNotFound,
+ "sandbox not found",
+ nil,
+ )
+ }
+ delete(c.sandboxes, sandboxID)
+ return nil
+}
+
+func (c *fakeRemoteClient) Exec(
+ _ context.Context,
+ _ RemoteSandboxHandle,
+ request RemoteExecRequest,
+) (*RemoteExecResult, error) {
+ c.mu.Lock()
+ c.execRequests = append(c.execRequests, request)
+ c.mu.Unlock()
+ return &RemoteExecResult{ExitCode: 0}, nil
+}
+
+func (c *fakeRemoteClient) WriteFile(
+ context.Context,
+ RemoteSandboxHandle,
+ string,
+ []byte,
+) error {
+ return nil
+}
+
+func (c *fakeRemoteClient) ReadFile(
+ context.Context,
+ RemoteSandboxHandle,
+ string,
+) ([]byte, error) {
+ return nil, nil
+}
+
+func (c *fakeRemoteClient) ListDir(
+ context.Context,
+ RemoteSandboxHandle,
+ string,
+) ([]RemoteDirEntry, error) {
+ return nil, nil
+}
+
+func (c *fakeRemoteClient) MakeDir(_ context.Context, _ RemoteSandboxHandle, path string) error {
+ c.mu.Lock()
+ c.makeDirPaths = append(c.makeDirPaths, path)
+ c.mu.Unlock()
+ return nil
+}
+
+func (c *fakeRemoteClient) Remove(context.Context, RemoteSandboxHandle, string) error {
+ return nil
+}
+
+func (c *fakeRemoteClient) Stat(
+ context.Context,
+ RemoteSandboxHandle,
+ string,
+) (*RemoteStatEntry, error) {
+ return nil, nil
+}
+
+func (c *fakeRemoteClient) addSandbox(
+ id string,
+ templateID string,
+ state RemoteSandboxState,
+ metadata map[string]string,
+ startedAt time.Time,
+) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.sandboxes[id] = &fakeRemoteRecord{
+ id: id,
+ templateID: templateID,
+ state: state,
+ rawState: string(state),
+ metadata: cloneStringMap(metadata),
+ startedAt: startedAt,
+ }
+}
+
+func (c *fakeRemoteClient) counts() (creates, connects, gets, lists, deletes int) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.createCount, len(c.connectIDs), len(c.getIDs), c.listCount, len(c.deleteIDs)
+}
+
+func (c *fakeRemoteClient) hasSandbox(id string) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ _, ok := c.sandboxes[id]
+ return ok
+}
+
+func (c *fakeRemoteClient) handle(record *fakeRemoteRecord) RemoteSandboxHandle {
+ return &fakeRemoteHandle{
+ id: record.id,
+ provider: c.provider,
+ metadata: cloneStringMap(record.metadata),
+ }
+}
+
+func (c *fakeRemoteClient) summary(record *fakeRemoteRecord) *RemoteSandboxSummary {
+ return &RemoteSandboxSummary{
+ ID: record.id,
+ TemplateID: record.templateID,
+ State: record.state,
+ RawState: record.rawState,
+ Metadata: cloneStringMap(record.metadata),
+ StartedAt: record.startedAt,
+ }
+}
+
+func cloneStringMap(source map[string]string) map[string]string {
+ if source == nil {
+ return nil
+ }
+ result := make(map[string]string, len(source))
+ for key, value := range source {
+ result[key] = value
+ }
+ return result
+}
+
+func metadataContains(candidate, required map[string]string) bool {
+ for key, value := range required {
+ if candidate[key] != value {
+ return false
+ }
+ }
+ return true
+}
+
+func stateMatches(candidate RemoteSandboxState, allowed []RemoteSandboxState) bool {
+ if len(allowed) == 0 {
+ return true
+ }
+ for _, state := range allowed {
+ if candidate == state {
+ return true
+ }
+ }
+ return false
+}
+
+var _ RemoteSandboxClient = (*fakeRemoteClient)(nil)
diff --git a/internal/sandbox/remote_sandbox.go b/internal/sandbox/remote_sandbox.go
new file mode 100644
index 000000000..a3dc1faf8
--- /dev/null
+++ b/internal/sandbox/remote_sandbox.go
@@ -0,0 +1,249 @@
+// Package sandbox: provider-neutral remote Sandbox implementation.
+//
+// RemoteSandbox is the concrete Sandbox that speaks any RemoteSandboxClient
+// backend. It contains no Cube- or E2B-specific logic; every operation is
+// expressed against the RemoteSandboxClient contract and a RemoteSandboxHandle.
+//
+// SessionBoundManager uses it in two shapes:
+//
+// - 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.
+// - 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;
+// RemoteSandbox never creates or deletes anything in this mode.
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path"
+ "path/filepath"
+ "time"
+)
+
+// remoteScriptDir is the absolute directory inside every remote sandbox where
+// WeKnora uploads scripts before execution. Kept identical to the historical
+// Cube path so existing tenant scripts continue to reference /workspace files.
+const remoteScriptDir = "/workspace"
+
+// RemoteSandbox implements Sandbox on top of a RemoteSandboxClient. It is
+// intentionally stateless: no local mutexes, no cached handles. Higher layers
+// decide whether a call allocates a fresh sandbox or reuses an existing one.
+type RemoteSandbox struct {
+ client RemoteSandboxClient
+ createRequest RemoteCreateRequest
+}
+
+// NewRemoteSandbox builds a stateless RemoteSandbox. createRequest is the
+// template used for ephemeral Execute calls. Callers that only use
+// ExecuteOnHandle may pass a zero createRequest.
+func NewRemoteSandbox(client RemoteSandboxClient, createRequest RemoteCreateRequest) *RemoteSandbox {
+ return &RemoteSandbox{client: client, createRequest: createRequest}
+}
+
+// Type mirrors the underlying provider so callers can gate provider-specific
+// behaviour (see agent_service capability registration).
+func (s *RemoteSandbox) Type() SandboxType {
+ if s == nil || s.client == nil {
+ return SandboxTypeDisabled
+ }
+ return s.client.Provider()
+}
+
+// IsAvailable probes the provider's control plane. Returns true only when
+// Health succeeds within ctx.
+func (s *RemoteSandbox) IsAvailable(ctx context.Context) bool {
+ if s == nil || s.client == nil {
+ return false
+ }
+ return s.client.Health(ctx) == nil
+}
+
+// Cleanup is a no-op: RemoteSandbox holds no long-lived state. Session
+// cleanup lives in SessionBoundManager, which owns the authoritative binding.
+func (s *RemoteSandbox) Cleanup(context.Context) error { return nil }
+
+// Execute allocates a fresh sandbox, runs cfg's script, and always tears the
+// sandbox down. It is the ephemeral path used when a caller provides no
+// SessionID.
+func (s *RemoteSandbox) Execute(ctx context.Context, cfg *ExecuteConfig) (*ExecuteResult, error) {
+ if s == nil || s.client == nil {
+ return nil, ErrSandboxDisabled
+ }
+ if cfg == nil {
+ return nil, ErrInvalidScript
+ }
+ if s.createRequest.TemplateID == "" {
+ return nil, errors.New("sandbox: remote sandbox has no template configured")
+ }
+
+ execCtx, cancel := boundedExecuteContext(ctx, cfg)
+ defer cancel()
+
+ handle, err := s.client.Create(execCtx, s.createRequest)
+ if err != nil {
+ return nil, fmt.Errorf("remote sandbox: create: %w", err)
+ }
+ defer s.disposeEphemeral(ctx, handle)
+
+ return s.ExecuteOnHandle(execCtx, handle, cfg)
+}
+
+// ExecuteOnHandle runs cfg's script against an existing handle without
+// allocating or deleting the underlying sandbox. It is the persistent path
+// SessionBoundManager drives after resolving the session's handle.
+func (s *RemoteSandbox) ExecuteOnHandle(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ cfg *ExecuteConfig,
+) (*ExecuteResult, error) {
+ if s == nil || s.client == nil {
+ return nil, ErrSandboxDisabled
+ }
+ if handle == nil {
+ return nil, errors.New("sandbox: remote handle is required")
+ }
+ if cfg == nil {
+ return nil, ErrInvalidScript
+ }
+
+ content, err := readScriptContent(cfg)
+ if err != nil {
+ return nil, err
+ }
+ scriptName := filepath.Base(cfg.Script)
+ if scriptName == "" || scriptName == "." || scriptName == "/" {
+ return nil, ErrInvalidScript
+ }
+ remoteScript := path.Join(remoteScriptDir, scriptName)
+
+ if err := s.client.WriteFile(ctx, handle, remoteScript, content); err != nil {
+ return nil, fmt.Errorf("remote sandbox: upload script %s: %w", remoteScript, err)
+ }
+
+ timeout := effectiveTimeout(cfg, 0)
+ request := RemoteExecRequest{
+ Command: getInterpreter(remoteScript),
+ Args: append([]string{remoteScript}, cfg.Args...),
+ Stdin: cfg.Stdin,
+ Env: cfg.Env,
+ WorkDir: remoteScriptDir,
+ User: DefaultSandboxExecUser,
+ Timeout: timeout,
+ }
+
+ start := time.Now()
+ execResult, err := s.client.Exec(ctx, handle, request)
+ duration := time.Since(start)
+ return remoteExecuteResult(execResult, err, duration), nil
+}
+
+// disposeEphemeral deletes the sandbox after an ephemeral Execute completes.
+// Errors are logged inside the client's normalization layer; we swallow them
+// so the caller always sees the primary result.
+func (s *RemoteSandbox) disposeEphemeral(parent context.Context, handle RemoteSandboxHandle) {
+ if handle == nil || handle.ID() == "" {
+ return
+ }
+ cleanupCtx, cancel := context.WithTimeout(
+ context.WithoutCancel(parent),
+ remoteCleanupTimeout,
+ )
+ defer cancel()
+ _ = s.client.Delete(cleanupCtx, handle.ID())
+}
+
+// remoteCleanupTimeout bounds the detached delete issued after an ephemeral
+// Execute. Matches the manager's session-scoped cleanup budget so behaviour
+// stays predictable regardless of which path performs the cleanup.
+const remoteCleanupTimeout = 30 * time.Second
+
+// remoteExecuteResult projects RemoteExecResult onto WeKnora's ExecuteResult.
+// It preserves the timeout contract: a timeout returns a killed result with
+// exit code -1 and ErrTimeout as Error, never an error return.
+func remoteExecuteResult(result *RemoteExecResult, err error, duration time.Duration) *ExecuteResult {
+ if err != nil {
+ if IsRemoteInvalidRequest(err) {
+ return &ExecuteResult{
+ Duration: duration,
+ ExitCode: -1,
+ Error: err.Error(),
+ }
+ }
+ return &ExecuteResult{
+ Duration: duration,
+ ExitCode: -1,
+ Error: err.Error(),
+ }
+ }
+ if result == nil {
+ return &ExecuteResult{
+ Duration: duration,
+ ExitCode: -1,
+ Error: "sandbox: remote provider returned no result",
+ }
+ }
+ if result.Killed {
+ return &ExecuteResult{
+ Stdout: result.Stdout,
+ Stderr: result.Stderr,
+ Duration: result.Duration,
+ Killed: true,
+ ExitCode: -1,
+ Error: ErrTimeout.Error(),
+ }
+ }
+ return &ExecuteResult{
+ Stdout: result.Stdout,
+ Stderr: result.Stderr,
+ ExitCode: result.ExitCode,
+ Duration: result.Duration,
+ }
+}
+
+// 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.
+func readScriptContent(cfg *ExecuteConfig) ([]byte, error) {
+ if cfg.ScriptContent != "" {
+ return []byte(cfg.ScriptContent), nil
+ }
+ if cfg.Script == "" {
+ return nil, ErrInvalidScript
+ }
+ content, err := os.ReadFile(cfg.Script)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, ErrScriptNotFound
+ }
+ return nil, fmt.Errorf("remote sandbox: read script: %w", err)
+ }
+ return content, nil
+}
+
+// boundedExecuteContext returns a derived context with the effective timeout
+// applied. It is only used on the ephemeral path; persistent execution runs
+// under SessionBoundManager's context (which the lifecycle lock already
+// bounds).
+func boundedExecuteContext(parent context.Context, cfg *ExecuteConfig) (context.Context, context.CancelFunc) {
+ timeout := effectiveTimeout(cfg, 0)
+ if timeout <= 0 {
+ return parent, func() {}
+ }
+ return context.WithTimeout(parent, timeout)
+}
+
+func effectiveTimeout(cfg *ExecuteConfig, fallback time.Duration) time.Duration {
+ if cfg != nil && cfg.Timeout > 0 {
+ return cfg.Timeout
+ }
+ if fallback > 0 {
+ return fallback
+ }
+ return DefaultTimeout
+}
diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go
index 29f22cf62..51647b0e6 100644
--- a/internal/sandbox/sandbox.go
+++ b/internal/sandbox/sandbox.go
@@ -16,16 +16,62 @@ const (
SandboxTypeDocker SandboxType = "docker"
// SandboxTypeLocal uses local process with restrictions
SandboxTypeLocal 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.
+ SandboxTypeCube SandboxType = "cube"
+ // SandboxTypeE2B uses E2B's hosted MicroVM sandbox service.
+ SandboxTypeE2B SandboxType = "e2b"
// SandboxTypeDisabled means script execution is disabled
SandboxTypeDisabled SandboxType = "disabled"
)
+// IsNamedSandboxBackendType reports whether raw can be stored as a user-facing
+// named sandbox backend. Only remote session backends (cube/e2b) support
+// per-config credentials and session pinning; docker/local/disabled are
+// deployment-level or workspace-policy concerns.
+func IsNamedSandboxBackendType(raw string) bool {
+ switch SandboxType(raw) {
+ case SandboxTypeCube, SandboxTypeE2B:
+ return true
+ default:
+ return false
+ }
+}
+
// Default configuration values
const (
DefaultTimeout = 60 * time.Second
DefaultMemoryLimit = 256 * 1024 * 1024 // 256MB
DefaultCPULimit = 1.0 // 1 CPU core
DefaultDockerImage = "wechatopenai/weknora-sandbox:latest"
+
+ // DefaultCubeAPIURL is the default CubeAPI endpoint used when
+ // WEKNORA_SANDBOX_CUBE_API_URL is not configured.
+ DefaultCubeAPIURL = "http://127.0.0.1:33000"
+ // DefaultCubeProxyURL is the default CubeProxy endpoint (HTTP, port 80) used
+ // to reach the in-sandbox envd via host-header routing.
+ DefaultCubeProxyURL = "http://127.0.0.1:80"
+ // DefaultCubeSandboxDomain is the sandbox routing domain configured on
+ // CubeProxy (matches CUBE_API_SANDBOX_DOMAIN in the Cube deployment).
+ DefaultCubeSandboxDomain = "cube.app"
+ // DefaultCubeTemplate is the default template ID used to spawn Cube sandboxes.
+ DefaultCubeTemplate = "tpl-2b7911a5c3bb419a8745957a"
+ // DefaultCubeSandboxTTL is the Cube-side sandbox lifetime hint (in seconds)
+ // requested at creation; the sandbox is torn down by CubeMaster if the
+ // client goes silent for longer than this value.
+ DefaultCubeSandboxTTL = 30 * time.Minute
+ // DefaultCubeHTTPTimeout bounds a single HTTP call to the CubeAPI
+ // (excluding user script execution which has its own per-call timeout).
+ DefaultCubeHTTPTimeout = 30 * time.Second
+
+ // DefaultE2BSandboxTTL matches the E2B SDK's built-in default so an
+ // unset E2BSandboxTTL still yields a valid sandbox lifetime.
+ DefaultE2BSandboxTTL = 5 * time.Minute
+ // DefaultE2BHTTPTimeout bounds a single HTTP call to the E2B API.
+ DefaultE2BHTTPTimeout = 30 * time.Second
)
// Common errors
@@ -89,10 +135,6 @@ type ExecuteConfig struct {
// Env is additional environment variables
Env map[string]string
- // AllowedCmds is a whitelist of commands that can be executed
- // If empty, a default safe list is used
- AllowedCmds []string
-
// AllowNetwork enables network access (Docker only)
AllowNetwork bool
@@ -113,6 +155,12 @@ type ExecuteConfig struct {
// ScriptContent is the script content for validation (optional, will be read from file if not provided)
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.
+ SessionID string
}
// ExecuteResult contains the result of script execution
@@ -141,14 +189,6 @@ func (r *ExecuteResult) IsSuccess() bool {
return r.ExitCode == 0 && !r.Killed && r.Error == ""
}
-// GetOutput returns the combined stdout and stderr, preferring stdout
-func (r *ExecuteResult) GetOutput() string {
- if r.Stdout != "" {
- return r.Stdout
- }
- return r.Stderr
-}
-
// Config holds sandbox manager configuration
type Config struct {
// Type is the preferred sandbox type
@@ -174,9 +214,67 @@ type Config struct {
// MaxCPU is the maximum CPU cores
MaxCPU float64
+
+ // EnvVars are additional environment variables to set for the sandbox.
+ EnvVars map[string]string
+
+ // CubeAPIURL is the base URL of the CubeAPI (E2B-compatible) endpoint.
+ // Only used when Type == SandboxTypeCube. Example: "http://127.0.0.1:33000".
+ CubeAPIURL string
+
+ // CubeProxyURL is the base URL of the CubeProxy HTTP endpoint through which
+ // in-sandbox envd traffic is routed via host-header rewriting. Example:
+ // "http://127.0.0.1:80".
+ CubeProxyURL string
+
+ // CubeSandboxDomain matches CubeAPI's CUBE_API_SANDBOX_DOMAIN. It is used to
+ // build the Host header "<port>-<sandboxID>.<domain>" that CubeProxy relies
+ // on to route requests into the correct MicroVM.
+ CubeSandboxDomain string
+
+ // CubeAPIKey is the API key sent via X-API-Key. Leave empty when the Cube
+ // deployment does not enforce authentication.
+ CubeAPIKey string
+
+ // CubeTemplate is the default template ID used when creating sandboxes.
+ CubeTemplate string
+
+ // CubeSandboxTTL is the Cube-side lifetime hint (passed as `timeout` when
+ // creating a sandbox). CubeMaster will reap the MicroVM if the client stops
+ // touching it for longer than this duration.
+ CubeSandboxTTL time.Duration
+
+ // CubeHTTPTimeout bounds each HTTP call to CubeAPI. Zero uses the default.
+ CubeHTTPTimeout time.Duration
+
+ // E2BAPIKey is the E2B API key sent via X-API-Key. Only used when
+ // Type == SandboxTypeE2B.
+ E2BAPIKey string
+
+ // E2BAPIURL is the E2B control-plane endpoint. Empty defaults to
+ E2BAPIURL string
+
+ // E2BSandboxDomain is the domain envd traffic is routed through, e.g.
+ // "e2b.app". Empty defaults to the SDK's built-in.
+ E2BSandboxDomain string
+
+ // E2BTemplate is the E2B template ID used at sandbox creation.
+ E2BTemplate string
+
+ // E2BSandboxTTL is the E2B-side idle timeout hint.
+ E2BSandboxTTL time.Duration
+
+ // E2BHTTPTimeout bounds each HTTP call to the E2B API.
+ E2BHTTPTimeout time.Duration
}
-// DefaultConfig returns a default sandbox configuration
+// DefaultConfig returns a default sandbox configuration.
+//
+// It deliberately carries no Cube or E2B endpoint, credential or template: those
+// belong either to the deployment baseline (see applyCubeDeploymentDefaults) or
+// to a named config that spelled them out. Presetting them here once meant every
+// baseline silently offered a localhost Cube to configs that had never asked for
+// one.
func DefaultConfig() *Config {
return &Config{
Type: SandboxTypeLocal,
@@ -186,6 +284,8 @@ func DefaultConfig() *Config {
AllowedCommands: defaultAllowedCommands(),
MaxMemory: DefaultMemoryLimit,
MaxCPU: DefaultCPULimit,
+ CubeSandboxTTL: DefaultCubeSandboxTTL,
+ CubeHTTPTimeout: DefaultCubeHTTPTimeout,
}
}
@@ -222,7 +322,7 @@ func ValidateConfig(config *Config) error {
}
switch config.Type {
- case SandboxTypeDocker, SandboxTypeLocal, SandboxTypeDisabled:
+ case SandboxTypeDocker, SandboxTypeLocal, SandboxTypeCube, SandboxTypeE2B, SandboxTypeDisabled:
// Valid types
default:
return errors.New("invalid sandbox type")
diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go
index dfc1383ce..1e8bb2604 100644
--- a/internal/sandbox/sandbox_test.go
+++ b/internal/sandbox/sandbox_test.go
@@ -195,6 +195,24 @@ func TestNewDisabledManager(t *testing.T) {
}
}
+func TestIsNamedSandboxBackendType(t *testing.T) {
+ for _, tc := range []struct {
+ raw string
+ want bool
+ }{
+ {"cube", true},
+ {"e2b", true},
+ {"docker", false},
+ {"local", false},
+ {"disabled", false},
+ {"", false},
+ } {
+ if got := IsNamedSandboxBackendType(tc.raw); got != tc.want {
+ t.Fatalf("IsNamedSandboxBackendType(%q) = %v, want %v", tc.raw, got, tc.want)
+ }
+ }
+}
+
func TestExecuteResultHelpers(t *testing.T) {
// Test IsSuccess
successResult := &ExecuteResult{
@@ -221,14 +239,6 @@ func TestExecuteResultHelpers(t *testing.T) {
t.Error("Expected IsSuccess() to return false when killed")
}
- // Test GetOutput
- if successResult.GetOutput() != "output" {
- t.Errorf("Expected GetOutput() to return stdout, got %s", successResult.GetOutput())
- }
-
- if failResult.GetOutput() != "error" {
- t.Errorf("Expected GetOutput() to return stderr when stdout is empty, got %s", failResult.GetOutput())
- }
}
func TestPythonScriptExecution(t *testing.T) {
diff --git a/internal/sandbox/session_binding.go b/internal/sandbox/session_binding.go
new file mode 100644
index 000000000..c5c9beb14
--- /dev/null
+++ b/internal/sandbox/session_binding.go
@@ -0,0 +1,274 @@
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+ "unicode"
+)
+
+// SessionSandboxBindingVersion is the current persisted binding schema.
+const SessionSandboxBindingVersion = 1
+
+// SessionSandboxKey identifies one tenant-scoped persistent sandbox.
+type SessionSandboxKey struct {
+ TenantID uint64
+ SessionID string
+}
+
+// Validate rejects keys that cannot identify a tenant session.
+func (k SessionSandboxKey) Validate() error {
+ if k.TenantID == 0 || strings.TrimSpace(k.SessionID) == "" {
+ return errors.New("sandbox binding requires tenant and session")
+ }
+ if strings.ContainsAny(k.SessionID, "{}") {
+ return errors.New("sandbox binding session must not contain braces")
+ }
+ for _, r := range k.SessionID {
+ if unicode.IsControl(r) {
+ return errors.New("sandbox binding session must not contain control characters")
+ }
+ }
+ return nil
+}
+
+// SessionSandboxBinding records the remote sandbox assigned to a session.
+type SessionSandboxBinding struct {
+ Version int `json:"version"`
+ Provider RemoteProvider `json:"provider,omitempty"`
+ TenantID uint64 `json:"tenant_id"`
+ SessionID string `json:"session_id"`
+ SandboxID string `json:"sandbox_id"`
+ TemplateID string `json:"template_id"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
+// Validate checks a binding against the current schema and authoritative key.
+func (b SessionSandboxBinding) Validate(key SessionSandboxKey) error {
+ if err := key.Validate(); err != nil {
+ return err
+ }
+ if b.Version != SessionSandboxBindingVersion {
+ return fmt.Errorf(
+ "sandbox binding version must be %d, got %d",
+ SessionSandboxBindingVersion,
+ b.Version,
+ )
+ }
+ if !isRemoteProvider(b.Provider) {
+ return fmt.Errorf("unsupported sandbox binding provider %q", b.Provider)
+ }
+ if b.TenantID != key.TenantID || b.SessionID != key.SessionID {
+ return errors.New("sandbox binding identity does not match its key")
+ }
+ if strings.TrimSpace(b.SandboxID) == "" {
+ return errors.New("sandbox binding requires sandbox ID")
+ }
+ if strings.TrimSpace(b.TemplateID) == "" {
+ return errors.New("sandbox binding requires template ID")
+ }
+ if b.CreatedAt.IsZero() {
+ return errors.New("sandbox binding requires creation time")
+ }
+ return nil
+}
+
+// SessionSandboxBindingStore persists bindings and serializes lifecycle
+// transitions. Implementations must use create-if-absent and compare-delete
+// semantics.
+type SessionSandboxBindingStore interface {
+ Get(context.Context, SessionSandboxKey) (*SessionSandboxBinding, error)
+ Create(context.Context, SessionSandboxKey, SessionSandboxBinding) (bool, error)
+ DeleteIfMatch(
+ context.Context,
+ SessionSandboxKey,
+ RemoteProvider,
+ string,
+ ) (bool, error)
+ // WithLifecycleLock passes fn a request context carrying a separate
+ // ownership context. The ownership context survives caller cancellation
+ // but is canceled when exclusive lock ownership is lost.
+ WithLifecycleLock(context.Context, SessionSandboxKey, func(context.Context) error) error
+}
+
+type lifecycleOwnershipContextKey struct{}
+
+func withLifecycleOwnershipContext(
+ ctx context.Context,
+ ownershipCtx context.Context,
+) context.Context {
+ return context.WithValue(ctx, lifecycleOwnershipContextKey{}, ownershipCtx)
+}
+
+func lifecycleOwnershipContext(ctx context.Context) context.Context {
+ if ownershipCtx, ok := ctx.Value(lifecycleOwnershipContextKey{}).(context.Context); ok {
+ return ownershipCtx
+ }
+ // Unknown store implementations fail safe by retaining request/lock
+ // cancellation rather than detaching destructive cleanup.
+ return ctx
+}
+
+type memoryLifecycleLock struct {
+ semaphore chan struct{}
+ users int
+}
+
+// MemorySessionSandboxBindingStore is a process-local implementation intended
+// for tests and explicitly configured single-process deployments.
+type MemorySessionSandboxBindingStore struct {
+ mu sync.Mutex
+ bindings map[SessionSandboxKey]SessionSandboxBinding
+ locks map[SessionSandboxKey]*memoryLifecycleLock
+}
+
+// NewMemorySessionSandboxBindingStore creates an empty in-memory store.
+func NewMemorySessionSandboxBindingStore() *MemorySessionSandboxBindingStore {
+ return &MemorySessionSandboxBindingStore{
+ bindings: make(map[SessionSandboxKey]SessionSandboxBinding),
+ locks: make(map[SessionSandboxKey]*memoryLifecycleLock),
+ }
+}
+
+// Get returns the current binding, or nil when the session is unbound.
+func (s *MemorySessionSandboxBindingStore) Get(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (*SessionSandboxBinding, error) {
+ if err := key.Validate(); err != nil {
+ return nil, err
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ binding, ok := s.bindings[key]
+ if !ok {
+ return nil, nil
+ }
+ result := binding
+ return &result, nil
+}
+
+// Create stores a validated current-schema binding only if key is unbound.
+func (s *MemorySessionSandboxBindingStore) Create(
+ ctx context.Context,
+ key SessionSandboxKey,
+ binding SessionSandboxBinding,
+) (bool, error) {
+ if err := binding.Validate(key); err != nil {
+ return false, err
+ }
+ if err := ctx.Err(); err != nil {
+ return false, err
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if _, exists := s.bindings[key]; exists {
+ return false, nil
+ }
+ s.bindings[key] = binding
+ return true, nil
+}
+
+// DeleteIfMatch deletes only the expected provider and sandbox ID.
+func (s *MemorySessionSandboxBindingStore) DeleteIfMatch(
+ ctx context.Context,
+ key SessionSandboxKey,
+ provider RemoteProvider,
+ sandboxID string,
+) (bool, error) {
+ if err := validateBindingMatch(key, provider, sandboxID); err != nil {
+ return false, err
+ }
+ if err := ctx.Err(); err != nil {
+ return false, err
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ binding, exists := s.bindings[key]
+ if !exists || binding.Provider != provider || binding.SandboxID != sandboxID {
+ return false, nil
+ }
+ delete(s.bindings, key)
+ return true, nil
+}
+
+// WithLifecycleLock runs fn while holding the process-local lock for key.
+func (s *MemorySessionSandboxBindingStore) WithLifecycleLock(
+ ctx context.Context,
+ key SessionSandboxKey,
+ fn func(context.Context) error,
+) error {
+ if err := key.Validate(); err != nil {
+ return err
+ }
+ if fn == nil {
+ return errors.New("sandbox lifecycle lock callback is required")
+ }
+
+ s.mu.Lock()
+ lock := s.locks[key]
+ if lock == nil {
+ lock = &memoryLifecycleLock{semaphore: make(chan struct{}, 1)}
+ s.locks[key] = lock
+ }
+ lock.users++
+ s.mu.Unlock()
+
+ select {
+ case lock.semaphore <- struct{}{}:
+ case <-ctx.Done():
+ s.dropMemoryLifecycleLockUser(key, lock)
+ return ctx.Err()
+ }
+
+ defer func() {
+ <-lock.semaphore
+ s.dropMemoryLifecycleLockUser(key, lock)
+ }()
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ return fn(withLifecycleOwnershipContext(ctx, context.WithoutCancel(ctx)))
+}
+
+func (s *MemorySessionSandboxBindingStore) dropMemoryLifecycleLockUser(
+ key SessionSandboxKey,
+ lock *memoryLifecycleLock,
+) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ lock.users--
+ if lock.users == 0 {
+ delete(s.locks, key)
+ }
+}
+
+func validateBindingMatch(
+ key SessionSandboxKey,
+ provider RemoteProvider,
+ sandboxID string,
+) error {
+ if err := key.Validate(); err != nil {
+ return err
+ }
+ if !isRemoteProvider(provider) {
+ return fmt.Errorf("unsupported sandbox binding provider %q", provider)
+ }
+ if strings.TrimSpace(sandboxID) == "" {
+ return errors.New("sandbox binding match requires sandbox ID")
+ }
+ return nil
+}
+
+func isRemoteProvider(provider RemoteProvider) bool {
+ return provider == SandboxTypeCube || provider == SandboxTypeE2B
+}
diff --git a/internal/sandbox/session_binding_redis.go b/internal/sandbox/session_binding_redis.go
new file mode 100644
index 000000000..0c8dec385
--- /dev/null
+++ b/internal/sandbox/session_binding_redis.go
@@ -0,0 +1,184 @@
+package sandbox
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+ "unicode"
+
+ "github.com/redis/go-redis/v9"
+
+ "github.com/Tencent/WeKnora/internal/common/redislock"
+)
+
+const (
+ redisLifecycleLockLease = 60 * time.Second
+ redisLifecycleLockRenewInterval = 20 * time.Second
+)
+
+var deleteBindingIfMatchScript = redis.NewScript(`
+local raw = redis.call('GET', KEYS[1])
+if not raw then return 0 end
+local value = cjson.decode(raw)
+local provider = value['provider']
+if provider == ARGV[1] and value['sandbox_id'] == ARGV[2] then
+ return redis.call('DEL', KEYS[1])
+end
+return 0
+`)
+
+// RedisSessionSandboxBindingStore is the authoritative distributed store for
+// persistent remote-session bindings.
+type RedisSessionSandboxBindingStore struct {
+ client redis.UniversalClient
+ namespace string
+ lockLease time.Duration
+ lockRenewInterval time.Duration
+}
+
+// NewRedisSessionSandboxBindingStore creates a fail-closed Redis store.
+func NewRedisSessionSandboxBindingStore(
+ client redis.UniversalClient,
+ namespace string,
+) (*RedisSessionSandboxBindingStore, error) {
+ if client == nil {
+ return nil, errors.New("sandbox binding Redis client is required")
+ }
+ namespace = strings.TrimSpace(namespace)
+ if err := validateRedisNamespace(namespace); err != nil {
+ return nil, err
+ }
+ return &RedisSessionSandboxBindingStore{
+ client: client,
+ namespace: namespace,
+ lockLease: redisLifecycleLockLease,
+ lockRenewInterval: redisLifecycleLockRenewInterval,
+ }, nil
+}
+
+// Get returns the current binding, or nil when the session is unbound.
+func (s *RedisSessionSandboxBindingStore) Get(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (*SessionSandboxBinding, error) {
+ if err := key.Validate(); err != nil {
+ return nil, err
+ }
+ raw, err := s.client.Get(ctx, s.bindingKey(key)).Bytes()
+ if errors.Is(err, redis.Nil) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("get sandbox binding: %w", err)
+ }
+
+ var binding SessionSandboxBinding
+ if err := json.Unmarshal(raw, &binding); err != nil {
+ return nil, fmt.Errorf("decode sandbox binding: %w", err)
+ }
+ if err := binding.Validate(key); err != nil {
+ return nil, fmt.Errorf("validate sandbox binding: %w", err)
+ }
+ return &binding, nil
+}
+
+// Create stores a validated current-schema binding with SET NX and no
+// expiration.
+func (s *RedisSessionSandboxBindingStore) Create(
+ ctx context.Context,
+ key SessionSandboxKey,
+ binding SessionSandboxBinding,
+) (bool, error) {
+ if err := binding.Validate(key); err != nil {
+ return false, err
+ }
+ raw, err := json.Marshal(binding)
+ if err != nil {
+ return false, fmt.Errorf("encode sandbox binding: %w", err)
+ }
+ created, err := s.client.SetNX(ctx, s.bindingKey(key), raw, 0).Result()
+ if err != nil {
+ return false, fmt.Errorf("create sandbox binding: %w", err)
+ }
+ return created, nil
+}
+
+// DeleteIfMatch atomically deletes only the expected provider and sandbox ID.
+func (s *RedisSessionSandboxBindingStore) DeleteIfMatch(
+ ctx context.Context,
+ key SessionSandboxKey,
+ provider RemoteProvider,
+ sandboxID string,
+) (bool, error) {
+ if err := validateBindingMatch(key, provider, sandboxID); err != nil {
+ return false, err
+ }
+ deleted, err := deleteBindingIfMatchScript.Run(
+ ctx,
+ s.client,
+ []string{s.bindingKey(key)},
+ string(provider),
+ sandboxID,
+ ).Int64()
+ if err != nil {
+ return false, fmt.Errorf("delete sandbox binding: %w", err)
+ }
+ return deleted != 0, nil
+}
+
+// WithLifecycleLock serializes create, recover, replace, and delete transitions
+// across all WeKnora processes sharing Redis.
+func (s *RedisSessionSandboxBindingStore) WithLifecycleLock(
+ ctx context.Context,
+ key SessionSandboxKey,
+ fn func(context.Context) error,
+) error {
+ if err := key.Validate(); err != nil {
+ return err
+ }
+ if fn == nil {
+ return errors.New("sandbox lifecycle lock callback is required")
+ }
+ return redislock.WithRenewableLock(
+ ctx,
+ s.client,
+ s.lockKey(key),
+ s.lockLease,
+ s.lockRenewInterval,
+ func(lockCtx context.Context) error {
+ return fn(withLifecycleOwnershipContext(
+ lockCtx,
+ redislock.OwnershipContext(lockCtx),
+ ))
+ },
+ )
+}
+
+func (s *RedisSessionSandboxBindingStore) bindingKey(key SessionSandboxKey) string {
+ return "weknora:sandbox:session:{" + s.hashTag(key) + "}:binding"
+}
+
+func (s *RedisSessionSandboxBindingStore) lockKey(key SessionSandboxKey) string {
+ // Keep the historical suffix used by the saved multi-node Cube
+ // implementation so rolling upgrades serialize on the same lock.
+ return "weknora:sandbox:session:{" + s.hashTag(key) + "}:create-lock"
+}
+
+func (s *RedisSessionSandboxBindingStore) hashTag(key SessionSandboxKey) string {
+ return fmt.Sprintf("%s:%d:%s", s.namespace, key.TenantID, key.SessionID)
+}
+
+func validateRedisNamespace(namespace string) error {
+ if strings.ContainsAny(namespace, "{}") {
+ return errors.New("WEKNORA_REDIS_NAMESPACE must not contain braces")
+ }
+ for _, r := range namespace {
+ if unicode.IsControl(r) {
+ return errors.New("WEKNORA_REDIS_NAMESPACE must not contain control characters")
+ }
+ }
+ return nil
+}
diff --git a/internal/sandbox/session_binding_redis_test.go b/internal/sandbox/session_binding_redis_test.go
new file mode 100644
index 000000000..a8ab4ef8e
--- /dev/null
+++ b/internal/sandbox/session_binding_redis_test.go
@@ -0,0 +1,205 @@
+package sandbox
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/alicebob/miniredis/v2"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+)
+
+func newRedisBindingTestStore(
+ t *testing.T,
+) (*RedisSessionSandboxBindingStore, *redis.Client, *miniredis.Miniredis) {
+ t.Helper()
+
+ mini := miniredis.RunT(t)
+ client := redis.NewClient(&redis.Options{Addr: mini.Addr(), MaxRetries: -1})
+ t.Cleanup(func() { require.NoError(t, client.Close()) })
+ store, err := NewRedisSessionSandboxBindingStore(client, "test")
+ require.NoError(t, err)
+ return store, client, mini
+}
+
+func newTwoRedisBindingTestStores(
+ t *testing.T,
+) (*RedisSessionSandboxBindingStore, *RedisSessionSandboxBindingStore) {
+ t.Helper()
+
+ mini := miniredis.RunT(t)
+ newStore := func() *RedisSessionSandboxBindingStore {
+ client := redis.NewClient(&redis.Options{Addr: mini.Addr(), MaxRetries: -1})
+ t.Cleanup(func() { require.NoError(t, client.Close()) })
+ store, err := NewRedisSessionSandboxBindingStore(client, "test")
+ require.NoError(t, err)
+ return store
+ }
+ return newStore(), newStore()
+}
+
+func TestRedisSessionSandboxBindingStoreContract(t *testing.T) {
+ store, _, _ := newRedisBindingTestStore(t)
+ testSessionSandboxBindingStore(t, store)
+}
+
+func TestRedisSessionSandboxBindingStoreSeparatesTenants(t *testing.T) {
+ store, _, _ := newRedisBindingTestStore(t)
+ testSessionSandboxBindingTenantIsolation(t, store)
+}
+
+func TestRedisSessionSandboxBindingUsesHashTagAndNoTTL(t *testing.T) {
+ store, client, _ := newRedisBindingTestStore(t)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ bindingKey := store.bindingKey(key)
+ lockKey := store.lockKey(key)
+
+ require.Equal(t, "weknora:sandbox:session:{test:42:session-a}:binding", bindingKey)
+ require.Equal(t, "weknora:sandbox:session:{test:42:session-a}:create-lock", lockKey)
+
+ created, err := store.Create(context.Background(), key, validSessionSandboxBinding(key, "sandbox-a"))
+ require.NoError(t, err)
+ require.True(t, created)
+ require.Equal(t, time.Duration(-1), client.TTL(context.Background(), bindingKey).Val())
+}
+
+func TestRedisSessionSandboxBindingRejectsMissingProvider(t *testing.T) {
+ store, client, _ := newRedisBindingTestStore(t)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ incomplete := map[string]any{
+ "version": SessionSandboxBindingVersion,
+ "tenant_id": 42,
+ "session_id": "session-a",
+ "sandbox_id": "sandbox-a",
+ "template_id": "template-a",
+ "created_at": time.Unix(100, 0).UTC(),
+ }
+ raw, err := json.Marshal(incomplete)
+ require.NoError(t, err)
+ require.NoError(t, client.Set(context.Background(), store.bindingKey(key), raw, 0).Err())
+
+ _, err = store.Get(context.Background(), key)
+ require.Error(t, err)
+}
+
+func TestRedisSessionSandboxBindingRejectsMalformedOrMismatchedData(t *testing.T) {
+ store, client, _ := newRedisBindingTestStore(t)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+
+ require.NoError(t, client.Set(context.Background(), store.bindingKey(key), "{", 0).Err())
+ _, err := store.Get(context.Background(), key)
+ require.Error(t, err)
+
+ mismatch := validSessionSandboxBinding(
+ SessionSandboxKey{TenantID: 43, SessionID: "session-a"},
+ "sandbox-a",
+ )
+ raw, err := json.Marshal(mismatch)
+ require.NoError(t, err)
+ require.NoError(t, client.Set(context.Background(), store.bindingKey(key), raw, 0).Err())
+ _, err = store.Get(context.Background(), key)
+ require.Error(t, err)
+}
+
+func TestRedisSessionSandboxBindingFailsClosedWhenRedisStops(t *testing.T) {
+ store, _, mini := newRedisBindingTestStore(t)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ binding := validSessionSandboxBinding(key, "sandbox-a")
+ mini.Close()
+
+ _, err := store.Get(context.Background(), key)
+ require.Error(t, err)
+ _, err = store.Create(context.Background(), key, binding)
+ require.Error(t, err)
+ _, err = store.DeleteIfMatch(context.Background(), key, SandboxTypeCube, "sandbox-a")
+ require.Error(t, err)
+
+ called := false
+ err = store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
+ called = true
+ return nil
+ })
+ require.Error(t, err)
+ require.False(t, called)
+}
+
+func TestRedisSessionSandboxBindingValidatesConstructor(t *testing.T) {
+ _, err := NewRedisSessionSandboxBindingStore(nil, "test")
+ require.Error(t, err)
+
+ client := redis.NewClient(&redis.Options{Addr: "unused"})
+ t.Cleanup(func() { require.NoError(t, client.Close()) })
+ for _, namespace := range []string{"bad{namespace", "bad}namespace", "bad\nnamespace"} {
+ _, err = NewRedisSessionSandboxBindingStore(client, namespace)
+ require.Error(t, err)
+ }
+ _, err = NewRedisSessionSandboxBindingStore(client, "namespace:with-punctuation")
+ require.NoError(t, err)
+}
+
+func TestRedisLifecycleLockSerializesAcrossStores(t *testing.T) {
+ firstStore, secondStore := newTwoRedisBindingTestStores(t)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ firstEntered := make(chan struct{})
+ releaseFirst := make(chan struct{})
+ firstDone := make(chan error, 1)
+
+ go func() {
+ firstDone <- firstStore.WithLifecycleLock(context.Background(), key, func(context.Context) error {
+ close(firstEntered)
+ <-releaseFirst
+ return nil
+ })
+ }()
+ <-firstEntered
+
+ secondEntered := make(chan struct{})
+ secondDone := make(chan error, 1)
+ go func() {
+ secondDone <- secondStore.WithLifecycleLock(context.Background(), key, func(context.Context) error {
+ close(secondEntered)
+ return nil
+ })
+ }()
+
+ select {
+ case <-secondEntered:
+ t.Fatal("contender entered before the first owner released")
+ case <-time.After(50 * time.Millisecond):
+ }
+ close(releaseFirst)
+ require.NoError(t, <-firstDone)
+ select {
+ case <-secondEntered:
+ case <-time.After(time.Second):
+ t.Fatal("contender did not acquire after release")
+ }
+ require.NoError(t, <-secondDone)
+}
+
+func TestRedisLifecycleLockAllowsDifferentKeys(t *testing.T) {
+ firstStore, secondStore := newTwoRedisBindingTestStores(t)
+ firstKey := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ secondKey := SessionSandboxKey{TenantID: 43, SessionID: "session-a"}
+ firstEntered := make(chan struct{})
+ releaseFirst := make(chan struct{})
+ firstDone := make(chan error, 1)
+
+ go func() {
+ firstDone <- firstStore.WithLifecycleLock(context.Background(), firstKey, func(context.Context) error {
+ close(firstEntered)
+ <-releaseFirst
+ return nil
+ })
+ }()
+ <-firstEntered
+
+ err := secondStore.WithLifecycleLock(context.Background(), secondKey, func(context.Context) error {
+ return nil
+ })
+ require.NoError(t, err)
+ close(releaseFirst)
+ require.NoError(t, <-firstDone)
+}
diff --git a/internal/sandbox/session_binding_tenant_test.go b/internal/sandbox/session_binding_tenant_test.go
new file mode 100644
index 000000000..593650f86
--- /dev/null
+++ b/internal/sandbox/session_binding_tenant_test.go
@@ -0,0 +1,67 @@
+package sandbox
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func newTenantKeyTestManager(t *testing.T) (*SessionBoundManager, *fakeRemoteClient) {
+ t.Helper()
+
+ client := newFakeRemoteClient(SandboxTypeCube)
+ cfg := DefaultConfig()
+ cfg.CubeTemplate = "tpl-test"
+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
+ Config: cfg,
+ Client: client,
+ Store: NewMemorySessionSandboxBindingStore(),
+ Checker: &fakeSessionExistenceChecker{exists: true},
+ SkipHealthProbe: true,
+ })
+ require.NoError(t, err)
+ return mgr, client
+}
+
+// A shared agent executes under the agent owner's tenant so its models, KBs and
+// named sandbox config resolve in the sharing workspace. Session deletion,
+// however, runs from a plain DELETE whose only tenant is the session's own.
+//
+// If the binding were keyed by the borrowed tenant, that teardown would look up
+// a key nobody wrote, silently leave the MicroVM running, and — because session
+// sandboxes are created with onTimeout=pause — leak a paused instance that keeps
+// billing with nobody holding its ID.
+func TestSessionBindingSurvivesBorrowedTenantAcrossDestroy(t *testing.T) {
+ const sessionOwner, agentOwner = uint64(7), uint64(99)
+
+ mgr, client := newTenantKeyTestManager(t)
+
+ // Execution: borrowed tenant in TenantID, session owner recorded alongside.
+ execCtx := context.WithValue(context.Background(), types.TenantIDContextKey, agentOwner)
+ execCtx = types.WithSandboxTenantID(execCtx, sessionOwner)
+ _, err := mgr.Execute(execCtx, &ExecuteConfig{
+ SessionID: "session-shared",
+ SkipValidation: true,
+ ScriptContent: "print('ok')\n",
+ Script: "hello.py",
+ })
+ require.NoError(t, err)
+
+ client.mu.Lock()
+ created := client.createCount
+ client.mu.Unlock()
+ require.Equal(t, 1, created, "execution should have provisioned one sandbox")
+
+ // Teardown: only the session's own tenant is known here, and no sandbox
+ // tenant key is set — exactly what sessionService.destroyBoundSandbox does.
+ destroyCtx := context.WithValue(context.Background(), types.TenantIDContextKey, sessionOwner)
+ require.NoError(t, mgr.DestroySession(destroyCtx, "session-shared"))
+
+ client.mu.Lock()
+ deleted := append([]string(nil), client.deleteIDs...)
+ client.mu.Unlock()
+ require.Len(t, deleted, 1, "teardown must reach the sandbox execution created")
+}
diff --git a/internal/sandbox/session_binding_test.go b/internal/sandbox/session_binding_test.go
new file mode 100644
index 000000000..6f64dded5
--- /dev/null
+++ b/internal/sandbox/session_binding_test.go
@@ -0,0 +1,182 @@
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func validSessionSandboxBinding(key SessionSandboxKey, sandboxID string) SessionSandboxBinding {
+ return SessionSandboxBinding{
+ Version: SessionSandboxBindingVersion,
+ Provider: SandboxTypeCube,
+ TenantID: key.TenantID,
+ SessionID: key.SessionID,
+ SandboxID: sandboxID,
+ TemplateID: "template-a",
+ CreatedAt: time.Unix(100, 0).UTC(),
+ }
+}
+
+func testSessionSandboxBindingStore(t *testing.T, store SessionSandboxBindingStore) {
+ t.Helper()
+
+ ctx := context.Background()
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ first := validSessionSandboxBinding(key, "sandbox-a")
+
+ got, err := store.Get(ctx, key)
+ require.NoError(t, err)
+ require.Nil(t, got)
+
+ created, err := store.Create(ctx, key, first)
+ require.NoError(t, err)
+ require.True(t, created)
+
+ got, err = store.Get(ctx, key)
+ require.NoError(t, err)
+ require.Equal(t, &first, got)
+
+ created, err = store.Create(ctx, key, validSessionSandboxBinding(key, "sandbox-b"))
+ require.NoError(t, err)
+ require.False(t, created)
+
+ deleted, err := store.DeleteIfMatch(ctx, key, SandboxTypeE2B, "sandbox-a")
+ require.NoError(t, err)
+ require.False(t, deleted)
+ deleted, err = store.DeleteIfMatch(ctx, key, SandboxTypeCube, "sandbox-b")
+ require.NoError(t, err)
+ require.False(t, deleted)
+ deleted, err = store.DeleteIfMatch(ctx, key, SandboxTypeCube, "sandbox-a")
+ require.NoError(t, err)
+ require.True(t, deleted)
+}
+
+func testSessionSandboxBindingTenantIsolation(t *testing.T, store SessionSandboxBindingStore) {
+ t.Helper()
+
+ ctx := context.Background()
+ firstKey := SessionSandboxKey{TenantID: 42, SessionID: "shared-session"}
+ secondKey := SessionSandboxKey{TenantID: 43, SessionID: "shared-session"}
+
+ created, err := store.Create(ctx, firstKey, validSessionSandboxBinding(firstKey, "sandbox-a"))
+ require.NoError(t, err)
+ require.True(t, created)
+ created, err = store.Create(ctx, secondKey, validSessionSandboxBinding(secondKey, "sandbox-b"))
+ require.NoError(t, err)
+ require.True(t, created)
+
+ first, err := store.Get(ctx, firstKey)
+ require.NoError(t, err)
+ second, err := store.Get(ctx, secondKey)
+ require.NoError(t, err)
+ require.Equal(t, "sandbox-a", first.SandboxID)
+ require.Equal(t, "sandbox-b", second.SandboxID)
+}
+
+func TestMemorySessionSandboxBindingStoreContract(t *testing.T) {
+ t.Parallel()
+ testSessionSandboxBindingStore(t, NewMemorySessionSandboxBindingStore())
+}
+
+func TestMemorySessionSandboxBindingStoreSeparatesTenants(t *testing.T) {
+ t.Parallel()
+ testSessionSandboxBindingTenantIsolation(t, NewMemorySessionSandboxBindingStore())
+}
+
+func TestSessionSandboxBindingValidation(t *testing.T) {
+ t.Parallel()
+
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ require.NoError(t, key.Validate())
+ require.Error(t, (SessionSandboxKey{}).Validate())
+ require.Error(t, (SessionSandboxKey{TenantID: 42, SessionID: " \t"}).Validate())
+ require.Error(t, (SessionSandboxKey{TenantID: 42, SessionID: "bad{session"}).Validate())
+ require.Error(t, (SessionSandboxKey{TenantID: 42, SessionID: "bad\nsession"}).Validate())
+
+ valid := validSessionSandboxBinding(key, "sandbox-a")
+ require.NoError(t, valid.Validate(key))
+
+ tests := []SessionSandboxBinding{
+ {Version: SessionSandboxBindingVersion + 1, Provider: SandboxTypeCube, TenantID: 42, SessionID: "session-a", SandboxID: "sandbox-a"},
+ {Version: SessionSandboxBindingVersion, TenantID: 42, SessionID: "session-a", SandboxID: "sandbox-a"},
+ {Version: SessionSandboxBindingVersion, Provider: "unknown", TenantID: 42, SessionID: "session-a", SandboxID: "sandbox-a"},
+ {Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube, TenantID: 43, SessionID: "session-a", SandboxID: "sandbox-a"},
+ {Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube, TenantID: 42, SessionID: "other", SandboxID: "sandbox-a"},
+ {Version: SessionSandboxBindingVersion, Provider: SandboxTypeCube, TenantID: 42, SessionID: "session-a"},
+ }
+ for _, binding := range tests {
+ require.Error(t, binding.Validate(key), "binding must be rejected: %+v", binding)
+ }
+}
+
+func TestMemoryLifecycleLockSerializesSameKey(t *testing.T) {
+ t.Parallel()
+
+ store := NewMemorySessionSandboxBindingStore()
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ var active atomic.Int32
+ var overlapped atomic.Bool
+ start := make(chan struct{})
+ done := make(chan error, 2)
+
+ for range 2 {
+ go func() {
+ <-start
+ done <- store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
+ if active.Add(1) != 1 {
+ overlapped.Store(true)
+ }
+ time.Sleep(10 * time.Millisecond)
+ active.Add(-1)
+ return nil
+ })
+ }()
+ }
+ close(start)
+
+ require.NoError(t, <-done)
+ require.NoError(t, <-done)
+ require.False(t, overlapped.Load())
+}
+
+func TestMemoryLifecycleLockHonorsContextAndCallbackError(t *testing.T) {
+ t.Parallel()
+
+ store := NewMemorySessionSandboxBindingStore()
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ firstDone := make(chan error, 1)
+ go func() {
+ firstDone <- store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
+ close(entered)
+ <-release
+ return nil
+ })
+ }()
+ <-entered
+
+ ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond)
+ defer cancel()
+ called := false
+ err := store.WithLifecycleLock(ctx, key, func(context.Context) error {
+ called = true
+ return nil
+ })
+ require.ErrorIs(t, err, context.DeadlineExceeded)
+ require.False(t, called)
+
+ close(release)
+ require.NoError(t, <-firstDone)
+
+ want := errors.New("callback failed")
+ err = store.WithLifecycleLock(context.Background(), key, func(context.Context) error {
+ return want
+ })
+ require.ErrorIs(t, err, want)
+}
diff --git a/internal/sandbox/session_lifecycle.go b/internal/sandbox/session_lifecycle.go
new file mode 100644
index 000000000..e38833684
--- /dev/null
+++ b/internal/sandbox/session_lifecycle.go
@@ -0,0 +1,599 @@
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+const (
+ remoteMetadataTenantID = "weknora_tenant_id"
+ remoteMetadataSessionID = "weknora_session_id"
+ remoteMetadataBindingVersion = "weknora_binding_version"
+ remoteMetadataProvider = "weknora_provider"
+
+ // remoteMetadataConfigID records which sandbox config created the sandbox.
+ // Two configs in one workspace may share a provider account, so cleanup
+ // must filter by config as well as tenant/session ownership.
+ remoteMetadataConfigID = "weknora_sandbox_config_id"
+)
+
+// ErrSandboxSessionDeleted reports that the owning WeKnora session no longer
+// exists. Callers must not execute work with the returned nil handle.
+var ErrSandboxSessionDeleted = errors.New("sandbox session no longer exists")
+
+// SessionExistenceChecker checks the tenant-scoped durable session record.
+type SessionExistenceChecker interface {
+ SessionExists(context.Context, SessionSandboxKey) (bool, error)
+}
+
+// remoteSessionLifecycle coordinates one provider's persistent sandboxes using
+// an authoritative binding store. It contains no provider-native types.
+type remoteSessionLifecycle struct {
+ client RemoteSandboxClient
+ bindings SessionSandboxBindingStore
+ sessionChecker SessionExistenceChecker
+ createRequest RemoteCreateRequest
+ cleanupTimeout time.Duration
+ sandboxConfigID string
+ now func() time.Time
+}
+
+func newRemoteSessionLifecycle(
+ client RemoteSandboxClient,
+ bindings SessionSandboxBindingStore,
+ sessionChecker SessionExistenceChecker,
+ createRequest RemoteCreateRequest,
+ cleanupTimeout time.Duration,
+ sandboxConfigID string,
+) (*remoteSessionLifecycle, error) {
+ if client == nil {
+ return nil, errors.New("remote sandbox client is required")
+ }
+ if bindings == nil {
+ return nil, errors.New("session sandbox binding store is required")
+ }
+ if sessionChecker == nil {
+ return nil, errors.New("session existence checker is required")
+ }
+ if !isRemoteProvider(client.Provider()) {
+ return nil, fmt.Errorf("unsupported remote sandbox provider %q", client.Provider())
+ }
+ if !client.Capabilities().SupportsReconnect {
+ return nil, fmt.Errorf("remote sandbox provider %q does not support reconnect", client.Provider())
+ }
+ if strings.TrimSpace(createRequest.TemplateID) == "" {
+ return nil, errors.New("remote sandbox template ID is required")
+ }
+ if cleanupTimeout <= 0 {
+ return nil, errors.New("remote sandbox cleanup timeout must be positive")
+ }
+ if strings.TrimSpace(sandboxConfigID) == "" {
+ sandboxConfigID = types.SandboxConfigIDGlobalDefault
+ }
+ createRequest.Metadata = cloneMetadata(createRequest.Metadata)
+ createRequest.EnvVars = cloneMetadata(createRequest.EnvVars)
+ return &remoteSessionLifecycle{
+ client: client,
+ bindings: bindings,
+ sessionChecker: sessionChecker,
+ createRequest: createRequest,
+ cleanupTimeout: cleanupTimeout,
+ sandboxConfigID: sandboxConfigID,
+ now: time.Now,
+ }, nil
+}
+
+// Resolve returns the current provider's sandbox for key, creating or
+// recovering one under the distributed lifecycle lock when necessary.
+func (l *remoteSessionLifecycle) Resolve(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (RemoteSandboxHandle, error) {
+ if err := key.Validate(); err != nil {
+ return nil, err
+ }
+
+ var handle RemoteSandboxHandle
+ err := l.bindings.WithLifecycleLock(ctx, key, func(lockCtx context.Context) error {
+ resolved, err := l.resolveLocked(lockCtx, key)
+ if err != nil {
+ return err
+ }
+ handle = resolved
+ return nil
+ })
+ if err != nil {
+ return nil, fmt.Errorf("resolve remote sandbox for session: %w", err)
+ }
+ if handle == nil {
+ return nil, errors.New("resolve remote sandbox returned no handle")
+ }
+ return handle, nil
+}
+
+// Destroy removes the bound remote sandbox and then compare-deletes its
+// binding. It is idempotent for absent and already-deleted sandboxes.
+func (l *remoteSessionLifecycle) Destroy(
+ ctx context.Context,
+ key SessionSandboxKey,
+) error {
+ if err := key.Validate(); err != nil {
+ return err
+ }
+ err := l.bindings.WithLifecycleLock(ctx, key, func(lockCtx context.Context) error {
+ binding, err := l.readBinding(lockCtx, key)
+ if err != nil || binding == nil {
+ return err
+ }
+ return l.destroyBindingLocked(lockCtx, key, *binding)
+ })
+ if err != nil {
+ return fmt.Errorf("destroy remote sandbox for session: %w", err)
+ }
+ return nil
+}
+
+func (l *remoteSessionLifecycle) resolveLocked(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (RemoteSandboxHandle, error) {
+ binding, err := l.readBinding(ctx, key)
+ if err != nil {
+ return nil, err
+ }
+
+ exists, err := l.sessionChecker.SessionExists(ctx, key)
+ if err != nil {
+ return nil, fmt.Errorf("check owning session: %w", err)
+ }
+ if !exists {
+ if binding != nil {
+ err = l.destroyBindingLocked(ctx, key, *binding)
+ }
+ return nil, errors.Join(ErrSandboxSessionDeleted, err)
+ }
+
+ if binding != nil && binding.Provider != l.client.Provider() {
+ deleted, err := l.bindings.DeleteIfMatch(
+ ctx,
+ key,
+ binding.Provider,
+ binding.SandboxID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("delete mismatched provider binding: %w", err)
+ }
+ if !deleted {
+ return nil, errors.New("mismatched provider binding changed during replacement")
+ }
+ binding = nil
+ }
+
+ if binding != nil {
+ handle, replace, err := l.connectBinding(ctx, *binding)
+ if err != nil {
+ return nil, err
+ }
+ if !replace {
+ return handle, nil
+ }
+ deleted, err := l.bindings.DeleteIfMatch(
+ ctx,
+ key,
+ binding.Provider,
+ binding.SandboxID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("delete terminal sandbox binding: %w", err)
+ }
+ if !deleted {
+ return nil, errors.New("terminal sandbox binding changed during replacement")
+ }
+ }
+
+ recovered, ok, err := l.recoverOwnedSandbox(ctx, key)
+ if err != nil {
+ return nil, err
+ }
+ if ok {
+ return recovered, nil
+ }
+ return l.createAndBind(ctx, key)
+}
+
+func (l *remoteSessionLifecycle) connectBinding(
+ ctx context.Context,
+ binding SessionSandboxBinding,
+) (RemoteSandboxHandle, bool, error) {
+ summary, err := l.client.Get(ctx, binding.SandboxID)
+ if err != nil {
+ if CanReplaceRemoteBinding(err) {
+ return nil, true, nil
+ }
+ return nil, false, fmt.Errorf("get bound remote sandbox: %w", err)
+ }
+ if summary == nil {
+ return nil, false, errors.New("remote sandbox Get returned nil summary")
+ }
+ if summary.ID != binding.SandboxID {
+ return nil, false, fmt.Errorf(
+ "remote sandbox Get returned ID %q for binding %q",
+ summary.ID,
+ binding.SandboxID,
+ )
+ }
+ if summary.State == RemoteStateTerminal {
+ return nil, true, nil
+ }
+
+ handle, err := l.client.Connect(ctx, binding.SandboxID)
+ if err != nil {
+ if CanReplaceRemoteBinding(err) {
+ return nil, true, nil
+ }
+ return nil, false, fmt.Errorf("connect bound remote sandbox: %w", err)
+ }
+ if err := l.validateHandle(handle, binding.SandboxID); err != nil {
+ return nil, false, err
+ }
+ return handle, false, nil
+}
+
+func (l *remoteSessionLifecycle) recoverOwnedSandbox(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (RemoteSandboxHandle, bool, error) {
+ capabilities := l.client.Capabilities()
+ if !capabilities.SupportsMetadata || !capabilities.SupportsListSandboxes {
+ return nil, false, nil
+ }
+
+ metadata := l.metadata(key)
+ summaries, err := l.client.List(ctx, RemoteListFilter{Metadata: metadata})
+ if err != nil {
+ return nil, false, fmt.Errorf("list owned remote sandboxes: %w", err)
+ }
+ sort.Slice(summaries, func(i, j int) bool {
+ left, right := summaries[i], summaries[j]
+ if left.StartedAt.Equal(right.StartedAt) {
+ return left.ID < right.ID
+ }
+ if left.StartedAt.IsZero() {
+ return false
+ }
+ if right.StartedAt.IsZero() {
+ return true
+ }
+ return left.StartedAt.Before(right.StartedAt)
+ })
+
+ for _, summary := range summaries {
+ if summary.ID == "" || summary.State == RemoteStateTerminal {
+ continue
+ }
+ if !metadataMatches(summary.Metadata, metadata) {
+ return nil, false, fmt.Errorf(
+ "remote provider returned sandbox %q outside metadata filter",
+ summary.ID,
+ )
+ }
+ handle, err := l.client.Connect(ctx, summary.ID)
+ if err != nil {
+ if CanReplaceRemoteBinding(err) {
+ continue
+ }
+ return nil, false, fmt.Errorf("connect owned remote sandbox: %w", err)
+ }
+ if err := l.validateHandle(handle, summary.ID); err != nil {
+ return nil, false, err
+ }
+ if err := l.cleanupOwnedDuplicates(ctx, summaries, summary.ID, metadata); err != nil {
+ return nil, false, err
+ }
+ templateID := summary.TemplateID
+ if templateID == "" {
+ templateID = l.createRequest.TemplateID
+ }
+ binding := l.newBinding(key, summary.ID, templateID, summary.StartedAt)
+ created, err := l.bindings.Create(ctx, key, binding)
+ if err != nil {
+ return nil, false, fmt.Errorf("bind owned remote sandbox: %w", err)
+ }
+ if created {
+ return handle, true, nil
+ }
+ winner, err := l.connectWinner(ctx, key)
+ if err != nil {
+ return nil, false, err
+ }
+ return winner, true, nil
+ }
+ return nil, false, nil
+}
+
+func (l *remoteSessionLifecycle) createAndBind(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (RemoteSandboxHandle, error) {
+ request := l.createRequest
+ request.Metadata = nil
+ if l.client.Capabilities().SupportsMetadata {
+ request.Metadata = cloneMetadata(l.createRequest.Metadata)
+ if request.Metadata == nil {
+ request.Metadata = make(map[string]string)
+ }
+ for metadataKey, value := range l.metadata(key) {
+ request.Metadata[metadataKey] = value
+ }
+ }
+ request.EnvVars = cloneMetadata(l.createRequest.EnvVars)
+
+ handle, err := l.client.Create(ctx, request)
+ if err != nil {
+ return nil, fmt.Errorf("create remote sandbox: %w", err)
+ }
+ if err := l.validateHandle(handle, ""); err != nil {
+ return nil, errors.Join(err, l.cleanupCreated(ctx, handle))
+ }
+
+ exists, checkErr := l.sessionChecker.SessionExists(ctx, key)
+ if checkErr != nil {
+ return nil, errors.Join(
+ fmt.Errorf("recheck owning session: %w", checkErr),
+ l.cleanupCreated(ctx, handle),
+ )
+ }
+ if !exists {
+ return nil, errors.Join(ErrSandboxSessionDeleted, l.cleanupCreated(ctx, handle))
+ }
+
+ binding := l.newBinding(
+ key,
+ handle.ID(),
+ request.TemplateID,
+ l.now().UTC(),
+ )
+ created, bindErr := l.bindings.Create(ctx, key, binding)
+ if bindErr != nil {
+ return nil, errors.Join(
+ fmt.Errorf("create sandbox binding: %w", bindErr),
+ l.cleanupCreated(ctx, handle),
+ )
+ }
+ if created {
+ return handle, nil
+ }
+
+ winner, winnerErr := l.readBinding(ctx, key)
+ if winnerErr != nil {
+ // The authoritative winner is unknown, so deleting this sandbox could
+ // destroy the resource another coordinator just bound.
+ return nil, fmt.Errorf("read winning sandbox binding: %w", winnerErr)
+ }
+ if winner != nil &&
+ winner.Provider == l.client.Provider() &&
+ winner.SandboxID == handle.ID() {
+ return handle, nil
+ }
+ if cleanupErr := l.cleanupCreated(ctx, handle); cleanupErr != nil {
+ return nil, fmt.Errorf("cleanup losing remote sandbox: %w", cleanupErr)
+ }
+ if winner == nil {
+ return nil, errors.New("sandbox binding create lost without a winner")
+ }
+ return l.connectKnownWinner(ctx, *winner)
+}
+
+func (l *remoteSessionLifecycle) connectWinner(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (RemoteSandboxHandle, error) {
+ winner, err := l.readBinding(ctx, key)
+ if err != nil {
+ return nil, err
+ }
+ if winner == nil {
+ return nil, errors.New("sandbox binding create lost without a winner")
+ }
+ return l.connectKnownWinner(ctx, *winner)
+}
+
+func (l *remoteSessionLifecycle) connectKnownWinner(
+ ctx context.Context,
+ winner SessionSandboxBinding,
+) (RemoteSandboxHandle, error) {
+ if winner.Provider != l.client.Provider() {
+ return nil, fmt.Errorf(
+ "sandbox binding winner uses provider %q, current provider is %q",
+ winner.Provider,
+ l.client.Provider(),
+ )
+ }
+ handle, replace, err := l.connectBinding(ctx, winner)
+ if err != nil {
+ return nil, err
+ }
+ if replace {
+ return nil, errors.New("sandbox binding winner is already terminal")
+ }
+ return handle, nil
+}
+
+func (l *remoteSessionLifecycle) cleanupOwnedDuplicates(
+ ctx context.Context,
+ summaries []RemoteSandboxSummary,
+ selectedID string,
+ metadata map[string]string,
+) error {
+ for _, candidate := range summaries {
+ if candidate.ID == "" ||
+ candidate.ID == selectedID ||
+ candidate.State == RemoteStateTerminal {
+ continue
+ }
+ if !metadataMatches(candidate.Metadata, metadata) {
+ return fmt.Errorf(
+ "remote provider returned sandbox %q outside metadata filter",
+ candidate.ID,
+ )
+ }
+ if err := l.cleanupSandboxID(ctx, candidate.ID); err != nil {
+ return fmt.Errorf(
+ "delete duplicate owned remote sandbox %q: %w",
+ candidate.ID,
+ err,
+ )
+ }
+ }
+ return nil
+}
+
+func (l *remoteSessionLifecycle) destroyBindingLocked(
+ ctx context.Context,
+ key SessionSandboxKey,
+ binding SessionSandboxBinding,
+) error {
+ if binding.Provider == l.client.Provider() {
+ err := l.client.Delete(ctx, binding.SandboxID)
+ if err != nil && !CanReplaceRemoteBinding(err) {
+ return fmt.Errorf("delete remote sandbox: %w", err)
+ }
+ }
+
+ deleted, err := l.bindings.DeleteIfMatch(
+ ctx,
+ key,
+ binding.Provider,
+ binding.SandboxID,
+ )
+ if err != nil {
+ return fmt.Errorf("delete sandbox binding: %w", err)
+ }
+ if deleted {
+ return nil
+ }
+ current, err := l.readBinding(ctx, key)
+ if err != nil {
+ return err
+ }
+ if current == nil {
+ return nil
+ }
+ return errors.New("sandbox binding changed during destroy")
+}
+
+func (l *remoteSessionLifecycle) readBinding(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (*SessionSandboxBinding, error) {
+ binding, err := l.bindings.Get(ctx, key)
+ if err != nil {
+ return nil, fmt.Errorf("get sandbox binding: %w", err)
+ }
+ if binding == nil {
+ return nil, nil
+ }
+ if err := binding.Validate(key); err != nil {
+ return nil, fmt.Errorf("validate sandbox binding: %w", err)
+ }
+ return binding, nil
+}
+
+func (l *remoteSessionLifecycle) cleanupCreated(
+ parent context.Context,
+ handle RemoteSandboxHandle,
+) error {
+ if handle == nil || handle.ID() == "" {
+ return errors.New("cannot clean up remote sandbox without an ID")
+ }
+ return l.cleanupSandboxID(parent, handle.ID())
+}
+
+func (l *remoteSessionLifecycle) cleanupSandboxID(
+ parent context.Context,
+ sandboxID string,
+) error {
+ cleanupCtx, cancel := context.WithTimeout(
+ lifecycleOwnershipContext(parent),
+ l.cleanupTimeout,
+ )
+ defer cancel()
+ err := l.client.Delete(cleanupCtx, sandboxID)
+ if err != nil && !CanReplaceRemoteBinding(err) {
+ return err
+ }
+ return nil
+}
+
+func (l *remoteSessionLifecycle) validateHandle(
+ handle RemoteSandboxHandle,
+ expectedID string,
+) error {
+ if handle == nil {
+ return errors.New("remote sandbox client returned nil handle")
+ }
+ if strings.TrimSpace(handle.ID()) == "" {
+ return errors.New("remote sandbox client returned handle without ID")
+ }
+ if expectedID != "" && handle.ID() != expectedID {
+ return fmt.Errorf(
+ "remote sandbox handle ID %q does not match expected %q",
+ handle.ID(),
+ expectedID,
+ )
+ }
+ if handle.Provider() != l.client.Provider() {
+ return fmt.Errorf(
+ "remote sandbox handle provider %q does not match client %q",
+ handle.Provider(),
+ l.client.Provider(),
+ )
+ }
+ return nil
+}
+
+func (l *remoteSessionLifecycle) newBinding(
+ key SessionSandboxKey,
+ sandboxID string,
+ templateID string,
+ createdAt time.Time,
+) SessionSandboxBinding {
+ if createdAt.IsZero() {
+ createdAt = l.now().UTC()
+ }
+ return SessionSandboxBinding{
+ Version: SessionSandboxBindingVersion,
+ Provider: l.client.Provider(),
+ TenantID: key.TenantID,
+ SessionID: key.SessionID,
+ SandboxID: sandboxID,
+ TemplateID: templateID,
+ CreatedAt: createdAt.UTC(),
+ }
+}
+
+func (l *remoteSessionLifecycle) metadata(key SessionSandboxKey) map[string]string {
+ return map[string]string{
+ remoteMetadataTenantID: strconv.FormatUint(key.TenantID, 10),
+ remoteMetadataSessionID: key.SessionID,
+ remoteMetadataBindingVersion: strconv.Itoa(SessionSandboxBindingVersion),
+ remoteMetadataProvider: string(l.client.Provider()),
+ remoteMetadataConfigID: l.sandboxConfigID,
+ }
+}
+
+func metadataMatches(candidate, required map[string]string) bool {
+ for key, value := range required {
+ if candidate[key] != value {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/sandbox/session_lifecycle_test.go b/internal/sandbox/session_lifecycle_test.go
new file mode 100644
index 000000000..0230751bb
--- /dev/null
+++ b/internal/sandbox/session_lifecycle_test.go
@@ -0,0 +1,899 @@
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+type fakeSessionExistenceChecker struct {
+ mu sync.Mutex
+ exists bool
+ err error
+ results []bool
+ calls int
+}
+
+func (c *fakeSessionExistenceChecker) SessionExists(
+ context.Context,
+ SessionSandboxKey,
+) (bool, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.calls++
+ if c.err != nil {
+ return false, c.err
+ }
+ if len(c.results) > 0 {
+ result := c.results[0]
+ c.results = c.results[1:]
+ return result, nil
+ }
+ return c.exists, nil
+}
+
+func (c *fakeSessionExistenceChecker) setExists(exists bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.exists = exists
+}
+
+type bindingStoreFaults struct {
+ base SessionSandboxBindingStore
+ getErr error
+ createErr error
+ deleteErr error
+ lockErr error
+ forceCreateFalse bool
+ beforeCreate func()
+ binding *SessionSandboxBinding
+}
+
+type cancelableLifecycleStore struct {
+ SessionSandboxBindingStore
+ mu sync.Mutex
+ cancel context.CancelFunc
+}
+
+func (s *cancelableLifecycleStore) WithLifecycleLock(
+ ctx context.Context,
+ _ SessionSandboxKey,
+ fn func(context.Context) error,
+) error {
+ lockCtx, cancel := context.WithCancel(ctx)
+ ownershipCtx, cancelOwnership := context.WithCancel(context.WithoutCancel(ctx))
+ s.mu.Lock()
+ s.cancel = func() {
+ cancelOwnership()
+ cancel()
+ }
+ s.mu.Unlock()
+ defer s.cancel()
+ return fn(withLifecycleOwnershipContext(lockCtx, ownershipCtx))
+}
+
+func (s *cancelableLifecycleStore) cancelLock() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.cancel != nil {
+ s.cancel()
+ }
+}
+
+func (s *bindingStoreFaults) Get(
+ ctx context.Context,
+ key SessionSandboxKey,
+) (*SessionSandboxBinding, error) {
+ if s.getErr != nil {
+ return nil, s.getErr
+ }
+ if s.binding != nil {
+ result := *s.binding
+ return &result, nil
+ }
+ return s.base.Get(ctx, key)
+}
+
+func (s *bindingStoreFaults) Create(
+ ctx context.Context,
+ key SessionSandboxKey,
+ binding SessionSandboxBinding,
+) (bool, error) {
+ if s.beforeCreate != nil {
+ s.beforeCreate()
+ }
+ if s.createErr != nil {
+ return false, s.createErr
+ }
+ if s.forceCreateFalse {
+ return false, nil
+ }
+ return s.base.Create(ctx, key, binding)
+}
+
+func (s *bindingStoreFaults) DeleteIfMatch(
+ ctx context.Context,
+ key SessionSandboxKey,
+ provider RemoteProvider,
+ sandboxID string,
+) (bool, error) {
+ if s.deleteErr != nil {
+ return false, s.deleteErr
+ }
+ return s.base.DeleteIfMatch(ctx, key, provider, sandboxID)
+}
+
+func (s *bindingStoreFaults) WithLifecycleLock(
+ ctx context.Context,
+ key SessionSandboxKey,
+ fn func(context.Context) error,
+) error {
+ if s.lockErr != nil {
+ return s.lockErr
+ }
+ return s.base.WithLifecycleLock(ctx, key, fn)
+}
+
+func newTestRemoteSessionLifecycle(
+ t *testing.T,
+ client RemoteSandboxClient,
+ store SessionSandboxBindingStore,
+ checker SessionExistenceChecker,
+) *remoteSessionLifecycle {
+ t.Helper()
+ lifecycle, err := newRemoteSessionLifecycle(
+ client,
+ store,
+ checker,
+ RemoteCreateRequest{
+ TemplateID: "template-a",
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: time.Hour,
+ Action: RemoteOnTimeoutPause,
+ },
+ },
+ time.Second,
+ "",
+ )
+ require.NoError(t, err)
+ return lifecycle
+}
+
+func TestRemoteSessionLifecycleCreatesOnceAcrossCoordinators(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ first := newTestRemoteSessionLifecycle(t, client, store, checker)
+ second := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+
+ start := make(chan struct{})
+ handles := make(chan RemoteSandboxHandle, 2)
+ errs := make(chan error, 2)
+ for _, lifecycle := range []*remoteSessionLifecycle{first, second} {
+ go func(current *remoteSessionLifecycle) {
+ <-start
+ handle, err := current.Resolve(context.Background(), key)
+ handles <- handle
+ errs <- err
+ }(lifecycle)
+ }
+ close(start)
+
+ require.NoError(t, <-errs)
+ require.NoError(t, <-errs)
+ firstHandle := <-handles
+ secondHandle := <-handles
+ require.NotNil(t, firstHandle)
+ require.NotNil(t, secondHandle)
+ require.Equal(t, firstHandle.ID(), secondHandle.ID())
+ creates, _, _, _, _ := client.counts()
+ require.Equal(t, 1, creates)
+}
+
+func TestRemoteSessionLifecycleAllowsDifferentKeysInParallel(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ firstKey := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ secondKey := SessionSandboxKey{TenantID: 42, SessionID: "session-b"}
+ firstEntered := make(chan struct{})
+ releaseFirst := make(chan struct{})
+
+ client.createHook = func(ctx context.Context, req RemoteCreateRequest) error {
+ if req.Metadata[remoteMetadataSessionID] != firstKey.SessionID {
+ return nil
+ }
+ close(firstEntered)
+ select {
+ case <-releaseFirst:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+
+ firstDone := make(chan error, 1)
+ go func() {
+ _, err := lifecycle.Resolve(context.Background(), firstKey)
+ firstDone <- err
+ }()
+ <-firstEntered
+
+ secondDone := make(chan error, 1)
+ go func() {
+ _, err := lifecycle.Resolve(context.Background(), secondKey)
+ secondDone <- err
+ }()
+ select {
+ case err := <-secondDone:
+ require.NoError(t, err)
+ case <-time.After(time.Second):
+ t.Fatal("different session was serialized behind the first")
+ }
+ close(releaseFirst)
+ require.NoError(t, <-firstDone)
+}
+
+func TestRemoteSessionLifecycleReplacesOnlyTerminalBinding(t *testing.T) {
+ tests := []struct {
+ name string
+ getErr error
+ state RemoteSandboxState
+ wantCreate int
+ wantErr bool
+ }{
+ {
+ name: "terminal state",
+ state: RemoteStateTerminal,
+ wantCreate: 1,
+ },
+ {
+ name: "unavailable error",
+ state: RemoteStateRunning,
+ getErr: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindUnavailable, "offline", nil),
+ wantErr: true,
+ },
+ {
+ name: "internal error",
+ state: RemoteStateRunning,
+ getErr: NewRemoteError(SandboxTypeCube, "Get", RemoteErrorKindInternal, "unknown", nil),
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ client.addSandbox("existing", "template-a", tt.state, nil, time.Now())
+ client.getErrs["existing"] = tt.getErr
+ created, err := store.Create(
+ context.Background(),
+ key,
+ validSessionSandboxBinding(key, "existing"),
+ )
+ require.NoError(t, err)
+ require.True(t, created)
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ if tt.wantErr {
+ require.Error(t, err)
+ require.Nil(t, handle)
+ binding, getErr := store.Get(context.Background(), key)
+ require.NoError(t, getErr)
+ require.Equal(t, "existing", binding.SandboxID)
+ } else {
+ require.NoError(t, err)
+ require.NotEqual(t, "existing", handle.ID())
+ }
+ creates, _, _, _, _ := client.counts()
+ require.Equal(t, tt.wantCreate, creates)
+ })
+ }
+}
+
+func TestRemoteSessionLifecycleProviderMismatchNeverUsesOldID(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeE2B)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ old := validSessionSandboxBinding(key, "cube-old")
+ old.Provider = SandboxTypeCube
+ created, err := store.Create(context.Background(), key, old)
+ require.NoError(t, err)
+ require.True(t, created)
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ require.Equal(t, SandboxTypeE2B, handle.Provider())
+ creates, connects, gets, _, deletes := client.counts()
+ require.Equal(t, 1, creates)
+ require.Zero(t, connects)
+ require.Zero(t, gets)
+ require.Zero(t, deletes)
+
+ binding, err := store.Get(context.Background(), key)
+ require.NoError(t, err)
+ require.Equal(t, SandboxTypeE2B, binding.Provider)
+ require.Equal(t, handle.ID(), binding.SandboxID)
+}
+
+func TestRemoteSessionLifecycleRecoversOldestMetadataCandidate(t *testing.T) {
+ for _, provider := range []RemoteProvider{SandboxTypeCube, SandboxTypeE2B} {
+ t.Run(string(provider), func(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(provider)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ metadata := lifecycle.metadata(key)
+ client.addSandbox("newer", "template-a", RemoteStateRunning, metadata, time.Unix(200, 0))
+ client.addSandbox("older", "template-a", RemoteStateRunning, metadata, time.Unix(100, 0))
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ require.Equal(t, "older", handle.ID())
+ creates, connects, _, lists, _ := client.counts()
+ require.Zero(t, creates)
+ require.Equal(t, 1, connects)
+ require.Equal(t, 1, lists)
+ })
+ }
+}
+
+func TestRemoteSessionLifecycleDeletesDuplicateMetadataCandidates(t *testing.T) {
+ for _, provider := range []RemoteProvider{SandboxTypeCube, SandboxTypeE2B} {
+ t.Run(string(provider), func(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(provider)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ metadata := lifecycle.metadata(key)
+ client.addSandbox("selected", "template-a", RemoteStateRunning, metadata, time.Unix(100, 0))
+ client.addSandbox("duplicate", "template-a", RemoteStateRunning, metadata, time.Unix(200, 0))
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ require.Equal(t, "selected", handle.ID())
+ require.True(t, client.hasSandbox("selected"))
+ require.False(t, client.hasSandbox("duplicate"))
+ _, _, _, _, deletes := client.counts()
+ require.Equal(t, 1, deletes)
+ })
+ }
+}
+
+func TestRemoteSessionLifecycleStopsDuplicateCleanupAfterLockLoss(t *testing.T) {
+ for _, provider := range []RemoteProvider{SandboxTypeCube, SandboxTypeE2B} {
+ t.Run(string(provider), func(t *testing.T) {
+ base := NewMemorySessionSandboxBindingStore()
+ store := &cancelableLifecycleStore{SessionSandboxBindingStore: base}
+ client := newFakeRemoteClient(provider)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ metadata := lifecycle.metadata(key)
+ client.addSandbox("selected", "template-a", RemoteStateRunning, metadata, time.Unix(100, 0))
+ client.addSandbox("duplicate", "template-a", RemoteStateRunning, metadata, time.Unix(200, 0))
+ client.deleteHook = func(ctx context.Context, sandboxID string) error {
+ if sandboxID == "duplicate" {
+ store.cancelLock()
+ }
+ return ctx.Err()
+ }
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.Error(t, err)
+ require.Nil(t, handle)
+ require.True(t, client.hasSandbox("selected"))
+ require.True(t, client.hasSandbox("duplicate"))
+ binding, getErr := base.Get(context.Background(), key)
+ require.NoError(t, getErr)
+ require.Nil(t, binding)
+ })
+ }
+}
+
+func TestE2BRemoteSessionLifecycleBindingStoreContract(t *testing.T) {
+ tests := []struct {
+ name string
+ newStore func(*testing.T) SessionSandboxBindingStore
+ }{
+ {
+ name: "memory",
+ newStore: func(*testing.T) SessionSandboxBindingStore {
+ return NewMemorySessionSandboxBindingStore()
+ },
+ },
+ {
+ name: "redis",
+ newStore: func(t *testing.T) SessionSandboxBindingStore {
+ store, _, _ := newRedisBindingTestStore(t)
+ return store
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ store := tt.newStore(t)
+ client := newFakeRemoteClient(SandboxTypeE2B)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ first := newTestRemoteSessionLifecycle(t, client, store, checker)
+ second := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-e2b"}
+
+ firstHandle, err := first.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ secondHandle, err := second.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ require.Equal(t, firstHandle.ID(), secondHandle.ID())
+ require.Equal(t, SandboxTypeE2B, secondHandle.Provider())
+
+ creates, _, _, _, _ := client.counts()
+ require.Equal(t, 1, creates)
+ binding, err := store.Get(context.Background(), key)
+ require.NoError(t, err)
+ require.NotNil(t, binding)
+ require.Equal(t, SandboxTypeE2B, binding.Provider)
+ require.Equal(t, firstHandle.ID(), binding.SandboxID)
+
+ require.NoError(t, second.Destroy(context.Background(), key))
+ require.False(t, client.hasSandbox(firstHandle.ID()))
+ binding, err = store.Get(context.Background(), key)
+ require.NoError(t, err)
+ require.Nil(t, binding)
+ })
+ }
+}
+
+func TestRemoteSessionLifecycleCleansCreatedSandboxWhenSessionDisappears(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{results: []bool{true, false}}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.ErrorIs(t, err, ErrSandboxSessionDeleted)
+ require.Nil(t, handle)
+ creates, _, _, _, deletes := client.counts()
+ require.Equal(t, 1, creates)
+ require.Equal(t, 1, deletes)
+ binding, getErr := store.Get(context.Background(), key)
+ require.NoError(t, getErr)
+ require.Nil(t, binding)
+}
+
+func TestRemoteSessionLifecycleCleansCreatedSandboxAfterCallerCancellation(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ ctx, cancel := context.WithCancel(context.Background())
+ client.afterCreate = func(RemoteSandboxHandle) {
+ cancel()
+ }
+
+ handle, err := lifecycle.Resolve(ctx, key)
+ require.ErrorIs(t, err, context.Canceled)
+ require.Nil(t, handle)
+ require.False(t, client.hasSandbox("cube-1"))
+ creates, _, _, _, deletes := client.counts()
+ require.Equal(t, 1, creates)
+ require.Equal(t, 1, deletes)
+ binding, getErr := store.Get(context.Background(), key)
+ require.NoError(t, getErr)
+ require.Nil(t, binding)
+}
+
+func TestRemoteSessionLifecycleCleansCreateLoserAndUsesWinner(t *testing.T) {
+ base := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ client.addSandbox("winner", "template-a", RemoteStateRunning, nil, time.Now())
+ store := &bindingStoreFaults{base: base, forceCreateFalse: true}
+ store.beforeCreate = func() {
+ created, err := base.Create(
+ context.Background(),
+ key,
+ validSessionSandboxBinding(key, "winner"),
+ )
+ require.NoError(t, err)
+ require.True(t, created)
+ }
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ require.Equal(t, "winner", handle.ID())
+ creates, connects, _, _, deletes := client.counts()
+ require.Equal(t, 1, creates)
+ require.Equal(t, 1, connects)
+ require.Equal(t, 1, deletes)
+}
+
+func TestRemoteSessionLifecycleDoesNotDeleteCreatedSandboxChosenAsWinner(t *testing.T) {
+ base := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ store := &bindingStoreFaults{base: base, forceCreateFalse: true}
+ store.beforeCreate = func() {
+ created, err := base.Create(
+ context.Background(),
+ key,
+ validSessionSandboxBinding(key, "cube-1"),
+ )
+ require.NoError(t, err)
+ require.True(t, created)
+ }
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ require.Equal(t, "cube-1", handle.ID())
+ require.True(t, client.hasSandbox("cube-1"))
+ _, _, _, _, deletes := client.counts()
+ require.Zero(t, deletes)
+}
+
+func TestRemoteSessionLifecycleCleansCreatedSandboxWhenBindingWriteFails(t *testing.T) {
+ base := NewMemorySessionSandboxBindingStore()
+ bindErr := errors.New("binding write failed")
+ cleanupErr := NewRemoteError(
+ SandboxTypeCube,
+ "Delete",
+ RemoteErrorKindUnavailable,
+ "cleanup unavailable",
+ nil,
+ )
+ store := &bindingStoreFaults{base: base, createErr: bindErr}
+ client := newFakeRemoteClient(SandboxTypeCube)
+ client.deleteErrs["cube-1"] = cleanupErr
+ lifecycle := newTestRemoteSessionLifecycle(
+ t,
+ client,
+ store,
+ &fakeSessionExistenceChecker{exists: true},
+ )
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.Nil(t, handle)
+ require.ErrorIs(t, err, bindErr)
+ require.ErrorIs(t, err, cleanupErr)
+ creates, _, _, _, deletes := client.counts()
+ require.Equal(t, 1, creates)
+ require.Equal(t, 1, deletes)
+ binding, getErr := base.Get(context.Background(), key)
+ require.NoError(t, getErr)
+ require.Nil(t, binding)
+}
+
+func TestRemoteSessionLifecycleDoesNotCreateWhenRecoveryListFails(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ listErr := NewRemoteError(
+ SandboxTypeCube,
+ "List",
+ RemoteErrorKindUnavailable,
+ "list unavailable",
+ nil,
+ )
+ client.listErr = listErr
+ lifecycle := newTestRemoteSessionLifecycle(
+ t,
+ client,
+ store,
+ &fakeSessionExistenceChecker{exists: true},
+ )
+
+ handle, err := lifecycle.Resolve(
+ context.Background(),
+ SessionSandboxKey{TenantID: 42, SessionID: "session-a"},
+ )
+ require.Nil(t, handle)
+ require.ErrorIs(t, err, listErr)
+ creates, _, _, lists, _ := client.counts()
+ require.Zero(t, creates)
+ require.Equal(t, 1, lists)
+}
+
+func TestRemoteSessionLifecycleFailsClosedOnBindingErrors(t *testing.T) {
+ fault := errors.New("binding unavailable")
+ tests := []struct {
+ name string
+ store SessionSandboxBindingStore
+ }{
+ {
+ name: "lock",
+ store: &bindingStoreFaults{
+ base: NewMemorySessionSandboxBindingStore(),
+ lockErr: fault,
+ },
+ },
+ {
+ name: "get",
+ store: &bindingStoreFaults{
+ base: NewMemorySessionSandboxBindingStore(),
+ getErr: fault,
+ },
+ },
+ {
+ name: "malformed binding",
+ store: &bindingStoreFaults{
+ base: NewMemorySessionSandboxBindingStore(),
+ binding: &SessionSandboxBinding{
+ Version: SessionSandboxBindingVersion,
+ TenantID: 42,
+ SessionID: "session-a",
+ SandboxID: "sandbox-a",
+ },
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ client := newFakeRemoteClient(SandboxTypeCube)
+ lifecycle := newTestRemoteSessionLifecycle(
+ t,
+ client,
+ tt.store,
+ &fakeSessionExistenceChecker{exists: true},
+ )
+ handle, err := lifecycle.Resolve(
+ context.Background(),
+ SessionSandboxKey{TenantID: 42, SessionID: "session-a"},
+ )
+ require.Error(t, err)
+ require.Nil(t, handle)
+ creates, connects, gets, lists, deletes := client.counts()
+ require.Zero(t, creates+connects+gets+lists+deletes)
+ })
+ }
+}
+
+func TestRemoteSessionLifecycleSerializesResolveAndDestroy(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ createEntered := make(chan struct{})
+ releaseCreate := make(chan struct{})
+ client.createHook = func(ctx context.Context, _ RemoteCreateRequest) error {
+ close(createEntered)
+ select {
+ case <-releaseCreate:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+
+ resolveDone := make(chan error, 1)
+ go func() {
+ _, err := lifecycle.Resolve(context.Background(), key)
+ resolveDone <- err
+ }()
+ <-createEntered
+
+ destroyDone := make(chan error, 1)
+ go func() {
+ destroyDone <- lifecycle.Destroy(context.Background(), key)
+ }()
+ select {
+ case err := <-destroyDone:
+ t.Fatalf("Destroy completed before Resolve released the lifecycle lock: %v", err)
+ case <-time.After(50 * time.Millisecond):
+ }
+
+ close(releaseCreate)
+ require.NoError(t, <-resolveDone)
+ require.NoError(t, <-destroyDone)
+ binding, err := store.Get(context.Background(), key)
+ require.NoError(t, err)
+ require.Nil(t, binding)
+ creates, _, _, _, deletes := client.counts()
+ require.Equal(t, 1, creates)
+ require.Equal(t, 1, deletes)
+}
+
+func TestRemoteSessionLifecycleDoesNotCreateForDeletedSession(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: false}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+
+ require.NoError(t, lifecycle.Destroy(context.Background(), key))
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.ErrorIs(t, err, ErrSandboxSessionDeleted)
+ require.Nil(t, handle)
+ creates, _, _, _, _ := client.counts()
+ require.Zero(t, creates)
+}
+
+func TestRemoteSessionLifecycleCleansBindingAfterSessionDeletion(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ lifecycle := newTestRemoteSessionLifecycle(t, client, store, checker)
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+
+ handle, err := lifecycle.Resolve(context.Background(), key)
+ require.NoError(t, err)
+ checker.setExists(false)
+
+ resolved, err := lifecycle.Resolve(context.Background(), key)
+ require.ErrorIs(t, err, ErrSandboxSessionDeleted)
+ require.Nil(t, resolved)
+ require.False(t, client.hasSandbox(handle.ID()))
+ binding, getErr := store.Get(context.Background(), key)
+ require.NoError(t, getErr)
+ require.Nil(t, binding)
+}
+
+func TestRemoteSessionLifecycleDestroySemantics(t *testing.T) {
+ t.Run("transient delete preserves binding", func(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ lifecycle := newTestRemoteSessionLifecycle(
+ t,
+ client,
+ store,
+ &fakeSessionExistenceChecker{exists: true},
+ )
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ client.addSandbox("existing", "template-a", RemoteStateRunning, nil, time.Now())
+ client.deleteErrs["existing"] = NewRemoteError(
+ SandboxTypeCube,
+ "Delete",
+ RemoteErrorKindUnavailable,
+ "offline",
+ nil,
+ )
+ created, err := store.Create(
+ context.Background(),
+ key,
+ validSessionSandboxBinding(key, "existing"),
+ )
+ require.NoError(t, err)
+ require.True(t, created)
+
+ require.Error(t, lifecycle.Destroy(context.Background(), key))
+ binding, err := store.Get(context.Background(), key)
+ require.NoError(t, err)
+ require.NotNil(t, binding)
+ })
+
+ t.Run("not found delete removes binding", func(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeCube)
+ lifecycle := newTestRemoteSessionLifecycle(
+ t,
+ client,
+ store,
+ &fakeSessionExistenceChecker{exists: true},
+ )
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ created, err := store.Create(
+ context.Background(),
+ key,
+ validSessionSandboxBinding(key, "missing"),
+ )
+ require.NoError(t, err)
+ require.True(t, created)
+
+ require.NoError(t, lifecycle.Destroy(context.Background(), key))
+ binding, err := store.Get(context.Background(), key)
+ require.NoError(t, err)
+ require.Nil(t, binding)
+ })
+
+ t.Run("provider mismatch only deletes binding", func(t *testing.T) {
+ store := NewMemorySessionSandboxBindingStore()
+ client := newFakeRemoteClient(SandboxTypeE2B)
+ lifecycle := newTestRemoteSessionLifecycle(
+ t,
+ client,
+ store,
+ &fakeSessionExistenceChecker{exists: true},
+ )
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ old := validSessionSandboxBinding(key, "cube-old")
+ old.Provider = SandboxTypeCube
+ created, err := store.Create(context.Background(), key, old)
+ require.NoError(t, err)
+ require.True(t, created)
+
+ require.NoError(t, lifecycle.Destroy(context.Background(), key))
+ _, _, _, _, deletes := client.counts()
+ require.Zero(t, deletes)
+ binding, err := store.Get(context.Background(), key)
+ require.NoError(t, err)
+ require.Nil(t, binding)
+ })
+
+ t.Run("binding delete failure is reported after remote deletion", func(t *testing.T) {
+ base := NewMemorySessionSandboxBindingStore()
+ deleteErr := errors.New("binding delete failed")
+ store := &bindingStoreFaults{base: base, deleteErr: deleteErr}
+ client := newFakeRemoteClient(SandboxTypeCube)
+ lifecycle := newTestRemoteSessionLifecycle(
+ t,
+ client,
+ store,
+ &fakeSessionExistenceChecker{exists: true},
+ )
+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
+ client.addSandbox("existing", "template-a", RemoteStateRunning, nil, time.Now())
+ created, err := base.Create(
+ context.Background(),
+ key,
+ validSessionSandboxBinding(key, "existing"),
+ )
+ require.NoError(t, err)
+ require.True(t, created)
+
+ err = lifecycle.Destroy(context.Background(), key)
+ require.ErrorIs(t, err, deleteErr)
+ require.False(t, client.hasSandbox("existing"))
+ binding, getErr := base.Get(context.Background(), key)
+ require.NoError(t, getErr)
+ require.NotNil(t, binding)
+ })
+}
+
+// Two configs in one workspace can point at the SAME provider account. Without
+// config_id in metadata, cleaning one config would delete the other's
+// sandboxes, so this tag is a correctness requirement, not a nicety.
+func TestLifecycleTagsSandboxWithConfigID(t *testing.T) {
+ lifecycle := newTestLifecycleWithConfigID(t, "cfg-42")
+
+ md := lifecycle.metadata(SessionSandboxKey{TenantID: 7, SessionID: "s-1"})
+
+ require.Equal(t, "cfg-42", md[remoteMetadataConfigID])
+ require.Equal(t, "7", md[remoteMetadataTenantID])
+ require.Equal(t, "s-1", md[remoteMetadataSessionID])
+}
+
+func TestLifecycleTagsGlobalDefaultConfigWithSentinel(t *testing.T) {
+ lifecycle := newTestLifecycleWithConfigID(t, "")
+
+ md := lifecycle.metadata(SessionSandboxKey{TenantID: 7, SessionID: "s-1"})
+
+ require.Equal(t, types.SandboxConfigIDGlobalDefault, md[remoteMetadataConfigID],
+ "an empty config ID must still be tagged, so listing can target it")
+}
+
+func newTestLifecycleWithConfigID(t *testing.T, configID string) *remoteSessionLifecycle {
+ t.Helper()
+ lifecycle, err := newRemoteSessionLifecycle(
+ newFakeRemoteClient(SandboxTypeCube),
+ NewMemorySessionSandboxBindingStore(),
+ &fakeSessionExistenceChecker{exists: true},
+ RemoteCreateRequest{TemplateID: "template-a"},
+ time.Minute,
+ configID,
+ )
+ require.NoError(t, err)
+ return lifecycle
+}
diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go
new file mode 100644
index 000000000..4d5ea1c4d
--- /dev/null
+++ b/internal/sandbox/session_manager.go
@@ -0,0 +1,867 @@
+// Package sandbox: session-bound Manager.
+//
+// SessionBoundManager keeps one persistent remote sandbox per tenant session.
+// It delegates all provider-specific work to a RemoteSandboxClient adapter and
+// treats the authoritative session→sandbox binding as external state that
+// lives in SessionSandboxBindingStore (Redis in production, memory in tests
+// and single-process deployments). This makes the manager provider-neutral
+// (Cube , E2B) and multi-instance safe: two WeKnora processes
+// concurrently servicing the same session never allocate duplicate sandboxes,
+// and a restart never loses the session's remote resource.
+//
+// Semantics:
+// - An Execute call with a non-empty ExecuteConfig.SessionID resolves the
+// session's remote sandbox (creating it lazily) and runs the script on
+// the resolved handle. All resolution goes through the lifecycle
+// coordinator so create/recover/replace/delete are serialised by the
+// distributed lifecycle lock.
+// - An Execute call with an empty SessionID falls through to a stateless
+// RemoteSandbox, which allocates a fresh sandbox, runs the script, and
+// tears the sandbox down after Execute returns.
+// - When the remote provider's Health probe fails at construction time and
+// config.FallbackEnabled is true, the manager falls back to LocalSandbox.
+// 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.
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "path"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// SessionInputRoot is reserved for durable user attachments restored from
+// file storage. Generated artifacts must remain under SessionOutputRoot.
+const SessionInputRoot = "/workspace/input"
+
+// SessionOutputRoot is where skill scripts write artifacts for collection.
+// The skills manager injects this path via skillOutputEnvVar; Execute
+// materialises the directory via envd before the script runs so scripts
+// do not depend on the template user being able to mkdir under /workspace.
+const SessionOutputRoot = "/workspace/output"
+
+// skillOutputEnvVar matches the skills manager's WEKNORA_SKILL_OUTPUT_DIR.
+const skillOutputEnvVar = "WEKNORA_SKILL_OUTPUT_DIR"
+
+// SessionWorkspaceRoot is the writable workspace root inside remote sandboxes.
+// shell_exec work_dir must stay underneath this path.
+const SessionWorkspaceRoot = "/workspace"
+
+// sessionArtifactDirBootstrapTimeout bounds the root-owned setup step that
+// grants DefaultSandboxExecUser write access to the artifact directory.
+const sessionArtifactDirBootstrapTimeout = 15 * time.Second
+
+// sessionLifecycleCleanupTimeout bounds the lifecycle coordinator's own
+// bookkeeping deletions (loser cleanup, orphan cleanup after session
+// disappearance).
+const sessionLifecycleCleanupTimeout = 30 * time.Second
+
+// SessionBoundManager is a sandbox.Manager that binds one remote sandbox per
+// tenant session. Concrete provider work is delegated to RemoteSandboxClient;
+// this type owns validation, fallback, and the mapping between application
+// concepts (ExecuteConfig, session-scoped shell/file APIs) and the provider-
+// neutral RemoteSandboxClient contract.
+type SessionBoundManager struct {
+ config *Config
+ validator *ScriptValidator
+
+ client RemoteSandboxClient
+ bindings SessionSandboxBindingStore
+ checker SessionExistenceChecker
+ lifecycle *remoteSessionLifecycle
+ ephemeral *RemoteSandbox
+
+ // fallback is used when the remote provider's health probe fails at
+ // construction time. Nil when the remote provider is healthy.
+ fallback Sandbox
+
+ // activeType is the effective sandbox type callers observe. It equals
+ // client.Provider() in the normal path and the fallback sandbox's Type()
+ // after Local fallback engages.
+ activeType SandboxType
+
+ // mu guards Cleanup's idempotency flag.
+ mu sync.RWMutex
+ closed bool
+}
+
+// SessionBoundManagerConfig bundles the wired dependencies. Test helpers and
+// the production container use it so callers only have to name the moving
+// parts they actually override.
+type SessionBoundManagerConfig struct {
+ Config *Config
+ Client RemoteSandboxClient
+ Store SessionSandboxBindingStore
+ Checker SessionExistenceChecker
+
+ // ConfigID identifies the tenant sandbox config this manager serves. It is
+ // stamped onto sandbox metadata so cleanup can target one config without
+ // touching another that shares the same provider account.
+ ConfigID string
+
+ // SkipHealthProbe skips the construction-time Health() round-trip and,
+ // with it, the Local fallback. Set by the per-tenant resolver, which
+ // builds a manager per request. See NewSessionBoundManager.
+ SkipHealthProbe bool
+}
+
+// NewSessionBoundManager wires the manager with an explicit RemoteSandboxClient
+// backend, binding store, and session existence checker. Every persistent
+// operation flows through these three dependencies; the manager never keeps
+// authoritative session→sandbox state locally.
+//
+// Provider identity comes from deps.Client.Provider() — not Config.Type —
+// so test harnesses and custom wiring that inject a different client backend
+// always project the correct template, TTL, and health timeout.
+//
+// When the client's Health probe fails and config.FallbackEnabled is true,
+// the manager transparently falls back to LocalSandbox for ephemeral Execute
+// calls. Session-scoped capabilities remain refused in that mode.
+func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManager, error) {
+ cfg := deps.Config
+ if cfg == nil {
+ cfg = DefaultConfig()
+ }
+ if err := ValidateConfig(cfg); err != nil {
+ return nil, fmt.Errorf("invalid sandbox config: %w", err)
+ }
+ if deps.Client == nil {
+ return nil, errors.New("session bound manager requires a RemoteSandboxClient")
+ }
+ if deps.Store == nil {
+ return nil, errors.New("session bound manager requires a SessionSandboxBindingStore")
+ }
+ if deps.Checker == nil {
+ return nil, errors.New("session bound manager requires a SessionExistenceChecker")
+ }
+
+ provider := deps.Client.Provider()
+ if !isRemoteProvider(provider) {
+ return nil, fmt.Errorf("sandbox: unsupported remote provider %q", provider)
+ }
+
+ // Apply the provider's tuning defaults so downstream code reads only
+ // non-zero TTL / timeout fields. Endpoint defaults are deliberately not
+ // applied here: this constructor also serves named configs, which must be
+ // told what they are missing rather than handed a built-in localhost value.
+ switch provider {
+ case SandboxTypeCube:
+ applyCubeRuntimeDefaults(cfg)
+ case SandboxTypeE2B:
+ applyE2BRuntimeDefaults(cfg)
+ }
+
+ // Build the provider-specific neutral create request using the
+ // provider's own template and TTL fields.
+ createRequest, err := buildSessionCreateRequest(provider, cfg)
+ if err != nil {
+ return nil, fmt.Errorf("session bound manager: %w", err)
+ }
+ // An empty template for the selected provider means the deployment is
+ // misconfigured. Fail early so operators get a clear message instead of
+ // a remote API error at the first sandbox allocation.
+ if strings.TrimSpace(createRequest.TemplateID) == "" {
+ return nil, fmt.Errorf(
+ "sandbox: %s template ID is required but not configured",
+ provider,
+ )
+ }
+
+ lifecycle, err := newRemoteSessionLifecycle(
+ deps.Client,
+ deps.Store,
+ deps.Checker,
+ createRequest,
+ sessionLifecycleCleanupTimeout,
+ deps.ConfigID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("session bound manager: %w", err)
+ }
+
+ m := &SessionBoundManager{
+ config: cfg,
+ validator: NewScriptValidator(),
+ client: deps.Client,
+ bindings: deps.Store,
+ checker: deps.Checker,
+ lifecycle: lifecycle,
+ ephemeral: NewRemoteSandbox(deps.Client, createRequest),
+ activeType: provider,
+ }
+
+ // Per-tenant managers are rebuilt on every request, so probing here would
+ // add a remote round-trip to each one. Skipping also disables the Local
+ // fallback below, which is deliberate: when a tenant explicitly configures
+ // a backend, silently running their scripts in a local process is a
+ // surprising, security-relevant downgrade. Failing loudly is correct.
+ if deps.SkipHealthProbe {
+ return m, nil
+ }
+
+ // Health probe uses the provider's own HTTP timeout.
+ probeCtx, cancel := context.WithTimeout(
+ context.Background(),
+ effectiveHTTPTimeout(provider, cfg),
+ )
+ defer cancel()
+ if err := deps.Client.Health(probeCtx); err != nil {
+ if !cfg.FallbackEnabled {
+ return nil, fmt.Errorf("remote sandbox provider unavailable: %w", err)
+ }
+ log.Printf("[sandbox] remote provider %s unhealthy (%v); falling back to local sandbox",
+ provider, err)
+ m.fallback = NewLocalSandbox(cfg)
+ m.activeType = m.fallback.Type()
+ }
+ return m, nil
+}
+
+// GetType reports the current effective sandbox type. Returns the fallback
+// type after Local fallback engages.
+func (m *SessionBoundManager) GetType() SandboxType {
+ if m == nil {
+ return SandboxTypeDisabled
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.activeType
+}
+
+// GetSandbox exposes a diagnostic Sandbox for callers that need to inspect
+// availability. Returns the fallback when engaged, otherwise a stateless
+// RemoteSandbox surface for the current provider.
+func (m *SessionBoundManager) GetSandbox() Sandbox {
+ if m == nil {
+ return nil
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ if m.fallback != nil {
+ return m.fallback
+ }
+ return m.ephemeral
+}
+
+// Execute is the shared entry point used by the DefaultManager compatibility
+// layer, the skills manager, and the ephemeral tool path. It applies script
+// security validation, then dispatches to the session-bound path (non-empty
+// SessionID) or the ephemeral path.
+func (m *SessionBoundManager) Execute(ctx context.Context, cfg *ExecuteConfig) (*ExecuteResult, error) {
+ if m == nil {
+ return nil, ErrSandboxDisabled
+ }
+ m.mu.RLock()
+ if m.closed {
+ m.mu.RUnlock()
+ return nil, ErrSandboxDisabled
+ }
+ fallback := m.fallback
+ m.mu.RUnlock()
+
+ if !cfg.SkipValidation {
+ if err := runScriptValidation(m.validator, cfg); err != nil {
+ log.Printf("[sandbox] security validation failed: %v", err)
+ return &ExecuteResult{
+ ExitCode: -1,
+ Error: err.Error(),
+ Stderr: fmt.Sprintf("Security validation failed: %v", err),
+ }, ErrSecurityViolation
+ }
+ }
+
+ if fallback != nil {
+ if strings.TrimSpace(cfg.SessionID) != "" {
+ return nil, fmt.Errorf(
+ "sandbox: session-scoped execution requires the remote provider (current mode: %s)",
+ m.fallback.Type(),
+ )
+ }
+ return fallback.Execute(ctx, cfg)
+ }
+ if strings.TrimSpace(cfg.SessionID) == "" {
+ return m.ephemeral.Execute(ctx, cfg)
+ }
+
+ handle, err := m.resolveSession(ctx, cfg.SessionID)
+ if err != nil {
+ return nil, err
+ }
+ m.ensureExecutionOutputDir(ctx, handle, cfg)
+ return m.ephemeral.ExecuteOnHandle(ctx, handle, cfg)
+}
+
+// ensureExecutionOutputDir creates the skill artifact directory and grants
+// DefaultSandboxExecUser write access before script execution. envd MakeDir
+// often leaves the path root-owned on Cube; the follow-up chown/chmod runs as
+// root via envd (empty User). Best-effort: failures are logged and do not
+// abort the upcoming script execution.
+func (m *SessionBoundManager) ensureExecutionOutputDir(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ cfg *ExecuteConfig,
+) {
+ if m == nil || m.client == nil || handle == nil {
+ return
+ }
+ outputDir := executionOutputDir(cfg)
+ if outputDir == "" {
+ return
+ }
+ execUser := DefaultSandboxExecUser
+ if err := m.client.MakeDir(ctx, handle, outputDir); err != nil {
+ log.Printf("[sandbox] ensure output dir %s failed: %v", outputDir, err)
+ return
+ }
+ quoted := strconv.Quote(outputDir)
+ line := fmt.Sprintf(
+ "chown %s:%s %s && chmod 775 %s",
+ execUser, execUser, quoted, quoted,
+ )
+ result, err := m.client.Exec(ctx, handle, RemoteExecRequest{
+ Shell: true,
+ Command: line,
+ Timeout: sessionArtifactDirBootstrapTimeout,
+ })
+ if err != nil {
+ log.Printf(
+ "[sandbox] grant output dir %s to %s failed: %v",
+ outputDir, execUser, err,
+ )
+ return
+ }
+ if result != nil && result.ExitCode != 0 {
+ log.Printf(
+ "[sandbox] grant output dir %s to %s: exit=%d stderr=%s",
+ outputDir, execUser, result.ExitCode, strings.TrimSpace(result.Stderr),
+ )
+ }
+}
+
+// executionOutputDir resolves the artifact directory for this Execute call.
+// It prefers WEKNORA_SKILL_OUTPUT_DIR from cfg.Env when the path stays under
+// SessionWorkspaceRoot; otherwise it falls back to SessionOutputRoot.
+func executionOutputDir(cfg *ExecuteConfig) string {
+ if cfg != nil && cfg.Env != nil {
+ if dir := strings.TrimSpace(cfg.Env[skillOutputEnvVar]); dir != "" {
+ if clean, err := cleanSessionWorkDir(dir); err == nil {
+ return clean
+ }
+ }
+ }
+ return SessionOutputRoot
+}
+
+// DestroySession removes the remote sandbox bound to sessionID (if any) and
+// the authoritative binding. Idempotent: succeeds on absent sessions.
+func (m *SessionBoundManager) DestroySession(ctx context.Context, sessionID string) error {
+ if m == nil || strings.TrimSpace(sessionID) == "" {
+ return nil
+ }
+ if m.remoteDisabled() {
+ return nil
+ }
+ key, err := m.sessionKey(ctx, sessionID)
+ if err != nil {
+ return err
+ }
+ return m.lifecycle.Destroy(ctx, key)
+}
+
+// EnsureSessionDir creates dir inside the session's live sandbox when one is
+// bound. It is a no-op when the session has no live binding; the skill
+// framework will materialise the directory during the next Execute call.
+func (m *SessionBoundManager) EnsureSessionDir(ctx context.Context, sessionID, dir string) error {
+ if strings.TrimSpace(dir) == "" {
+ return nil
+ }
+ handle, ok, err := m.lookupSessionHandle(ctx, sessionID)
+ if err != nil || !ok {
+ return err
+ }
+ if err := m.client.MakeDir(ctx, handle, dir); err != nil {
+ return fmt.Errorf("sandbox: ensure session dir %s: %w", dir, err)
+ }
+ return nil
+}
+
+// WriteSessionInputFile writes a durable attachment path into the session's
+// remote sandbox, provisioning the sandbox on first call. It is refused when
+// the manager has fallen back to Local (writing to the host would leak
+// attachments outside the tenant's isolation boundary).
+func (m *SessionBoundManager) WriteSessionInputFile(
+ ctx context.Context, sessionID, filePath string, content []byte,
+) error {
+ if err := m.requireRemoteBackend(); err != nil {
+ return err
+ }
+ if strings.TrimSpace(sessionID) == "" {
+ return errors.New("sandbox: session ID required for input staging")
+ }
+ clean, err := cleanSessionInputPath(filePath)
+ if err != nil {
+ return err
+ }
+ handle, err := m.resolveSession(ctx, sessionID)
+ if err != nil {
+ return err
+ }
+ if err := m.client.MakeDir(ctx, handle, path.Dir(clean)); err != nil {
+ return fmt.Errorf("sandbox: create input directory: %w", err)
+ }
+ if err := m.client.WriteFile(ctx, handle, clean, content); err != nil {
+ return fmt.Errorf("sandbox: write session input %s: %w", clean, err)
+ }
+ return nil
+}
+
+// RemoveSessionInputPath deletes a staged attachment. It is a no-op when the
+// session has no live sandbox and never provisions one.
+func (m *SessionBoundManager) RemoveSessionInputPath(
+ ctx context.Context, sessionID, targetPath string,
+) error {
+ if err := m.requireRemoteBackend(); err != nil {
+ return err
+ }
+ clean, err := cleanSessionInputPath(targetPath)
+ if err != nil {
+ return err
+ }
+ handle, ok, err := m.lookupSessionHandle(ctx, sessionID)
+ if err != nil || !ok {
+ return err
+ }
+ if err := m.client.Remove(ctx, handle, clean); err != nil {
+ return fmt.Errorf("sandbox: remove session input %s: %w", clean, err)
+ }
+ return nil
+}
+
+// ListSessionFiles walks dir under the session's live sandbox recursively.
+// Returns nil (no error) when the session has no bound sandbox so callers can
+// treat "no sandbox" and "empty output" uniformly.
+func (m *SessionBoundManager) ListSessionFiles(
+ ctx context.Context, sessionID, dir string,
+) ([]RemoteDirEntry, error) {
+ if strings.TrimSpace(dir) == "" {
+ return nil, errors.New("sandbox: dir required for ListSessionFiles")
+ }
+ handle, ok, err := m.lookupSessionHandle(ctx, sessionID)
+ if err != nil || !ok {
+ return nil, err
+ }
+ return m.listFilesRecursive(ctx, handle, dir)
+}
+
+// StatSessionFile returns metadata for a single file without downloading
+// contents. Returns an error when no sandbox is bound: callers of this
+// method already hold a path from a prior ListSessionFiles call and should
+// not race with reaper/destroy.
+func (m *SessionBoundManager) StatSessionFile(
+ ctx context.Context, sessionID, filePath string,
+) (*RemoteStatEntry, error) {
+ if strings.TrimSpace(filePath) == "" {
+ return nil, errors.New("sandbox: path required for StatSessionFile")
+ }
+ handle, ok, err := m.lookupSessionHandle(ctx, sessionID)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ return nil, fmt.Errorf("sandbox: no live sandbox for session %s", sessionID)
+ }
+ return m.client.Stat(ctx, handle, filePath)
+}
+
+// ReadSessionFile downloads a file from the session's live sandbox. Errors
+// when no sandbox is bound for the same reason as StatSessionFile.
+func (m *SessionBoundManager) ReadSessionFile(
+ ctx context.Context, sessionID, filePath string,
+) ([]byte, error) {
+ if strings.TrimSpace(filePath) == "" {
+ return nil, errors.New("sandbox: path required for ReadSessionFile")
+ }
+ handle, ok, err := m.lookupSessionHandle(ctx, sessionID)
+ if err != nil {
+ return nil, err
+ }
+ if !ok {
+ return nil, fmt.Errorf("sandbox: no live sandbox for session %s", sessionID)
+ }
+ return m.client.ReadFile(ctx, handle, filePath)
+}
+
+// ExecShellCommand runs a shell one-liner inside the session's persistent
+// sandbox. Fallback is explicitly refused so shell_exec never escapes onto
+// the host machine.
+func (m *SessionBoundManager) ExecShellCommand(
+ ctx context.Context,
+ sessionID string,
+ command string,
+ workDir string,
+ timeout time.Duration,
+ env map[string]string,
+) (*ExecuteResult, error) {
+ if err := m.requireRemoteBackend(); err != nil {
+ return nil, fmt.Errorf(
+ "sandbox: shell_exec requires the remote sandbox provider (current mode: %s)",
+ m.GetType(),
+ )
+ }
+ if strings.TrimSpace(sessionID) == "" {
+ return nil, errors.New("sandbox: session_id required for ExecShellCommand")
+ }
+ if strings.TrimSpace(command) == "" {
+ return nil, errors.New("sandbox: command required for ExecShellCommand")
+ }
+ if timeout <= 0 {
+ timeout = m.config.DefaultTimeout
+ }
+ if timeout <= 0 {
+ timeout = DefaultTimeout
+ }
+
+ workDir = strings.TrimSpace(workDir)
+ if workDir != "" {
+ cleanWorkDir, err := cleanSessionWorkDir(workDir)
+ if err != nil {
+ return nil, err
+ }
+ workDir = cleanWorkDir
+ }
+
+ handle, err := m.resolveSession(ctx, sessionID)
+ if err != nil {
+ return nil, err
+ }
+ if workDir != "" {
+ if mkErr := m.client.MakeDir(ctx, handle, workDir); mkErr != nil {
+ log.Printf("[sandbox] shell_exec: MakeDir %s failed (continuing): %v", workDir, mkErr)
+ }
+ }
+
+ start := time.Now()
+ execResult, execErr := m.client.Exec(ctx, handle, RemoteExecRequest{
+ Command: command,
+ Shell: true,
+ Env: env,
+ WorkDir: workDir,
+ Timeout: timeout,
+ })
+ duration := time.Since(start)
+ return remoteExecuteResult(execResult, execErr, duration), nil
+}
+
+// SessionShellExecutor advertises the shell-execution capability while a
+// real remote backend is active. Returns nil after Local fallback engages so
+// the tool layer refuses to run shell commands on the host machine.
+func (m *SessionBoundManager) SessionShellExecutor() SessionShellExecutor {
+ if m == nil || m.remoteDisabled() {
+ return nil
+ }
+ return m
+}
+
+// SessionFileStore advertises the session-scoped filesystem capability while
+// a real remote backend is active and the provider implements the enumeration
+// operations (ListDir / Stat / MakeDir / Remove).
+func (m *SessionBoundManager) SessionFileStore() SessionFileStore {
+ if m == nil || m.remoteDisabled() {
+ return nil
+ }
+ if !m.client.Capabilities().SupportsFilesystemEnumeration {
+ return nil
+ }
+ return m
+}
+
+// Cleanup marks the manager closed. Session sandboxes are not force-deleted
+// here: their lifecycle is authoritative in the binding store and would
+// leak to any other WeKnora replica if this replica reaped them on shutdown.
+// Providers reclaim idle sandboxes via their own timeout/pause policies.
+func (m *SessionBoundManager) Cleanup(ctx context.Context) error {
+ if m == nil {
+ return nil
+ }
+ m.mu.Lock()
+ if m.closed {
+ m.mu.Unlock()
+ return nil
+ }
+ m.closed = true
+ fallback := m.fallback
+ m.mu.Unlock()
+
+ if fallback != nil {
+ return fallback.Cleanup(ctx)
+ }
+ return nil
+}
+
+// --- internal helpers --------------------------------------------------------
+
+// resolveSession resolves (or lazily creates) the remote sandbox bound to
+// sessionID. Persistent path only.
+func (m *SessionBoundManager) resolveSession(
+ ctx context.Context,
+ sessionID string,
+) (RemoteSandboxHandle, error) {
+ key, err := m.sessionKey(ctx, sessionID)
+ if err != nil {
+ return nil, err
+ }
+ return m.lifecycle.Resolve(ctx, key)
+}
+
+// lookupSessionHandle reads the authoritative binding and, when one exists
+// with the current provider, connects to the remote sandbox without
+// allocating. Used by artifact / staging paths that must never provision.
+func (m *SessionBoundManager) lookupSessionHandle(
+ ctx context.Context,
+ sessionID string,
+) (RemoteSandboxHandle, bool, error) {
+ if m.remoteDisabled() || strings.TrimSpace(sessionID) == "" {
+ return nil, false, nil
+ }
+ key, err := m.sessionKey(ctx, sessionID)
+ if err != nil {
+ return nil, false, err
+ }
+ binding, err := m.bindings.Get(ctx, key)
+ if err != nil {
+ return nil, false, fmt.Errorf("sandbox: read session binding: %w", err)
+ }
+ if binding == nil || binding.Provider != m.client.Provider() {
+ return nil, false, nil
+ }
+ handle, err := m.client.Connect(ctx, binding.SandboxID)
+ if err != nil {
+ if CanReplaceRemoteBinding(err) {
+ return nil, false, nil
+ }
+ return nil, false, fmt.Errorf("sandbox: connect session sandbox: %w", err)
+ }
+ if handle == nil || handle.ID() != binding.SandboxID ||
+ handle.Provider() != m.client.Provider() {
+ return nil, false, errors.New("sandbox: remote handle does not match binding")
+ }
+ return handle, true, nil
+}
+
+func (m *SessionBoundManager) listFilesRecursive(
+ ctx context.Context,
+ handle RemoteSandboxHandle,
+ dir string,
+) ([]RemoteDirEntry, error) {
+ stat, err := m.client.Stat(ctx, handle, dir)
+ if err != nil {
+ if IsRemoteNotFound(err) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("sandbox: stat %s: %w", dir, err)
+ }
+ if stat == nil {
+ return nil, nil
+ }
+
+ stack := []string{dir}
+ var files []RemoteDirEntry
+ for len(stack) > 0 {
+ cur := stack[len(stack)-1]
+ stack = stack[:len(stack)-1]
+
+ entries, err := m.client.ListDir(ctx, handle, cur)
+ if err != nil {
+ return nil, err
+ }
+ for _, entry := range entries {
+ if entry.Path == "" {
+ entry.Path = path.Join(cur, entry.Name)
+ }
+ if entry.Type == RemoteEntryDir {
+ stack = append(stack, entry.Path)
+ continue
+ }
+ if entry.Type == RemoteEntryFile {
+ files = append(files, entry)
+ }
+ }
+ }
+ return files, nil
+}
+
+// sessionKey resolves the tenant-scoped binding key. Tenant ID comes from the
+// request context; empty tenant is treated as a caller error to keep session
+// bindings globally addressable in Redis.
+//
+// It reads the session-owner tenant rather than the ambient request tenant so
+// that a shared agent — which runs under the agent owner's workspace so its
+// models, KBs and named sandbox configs resolve there — still binds its sandbox
+// under the session's own tenant. Session deletion tears the sandbox down from a
+// request that knows only that tenant, so any other choice would strand the
+// MicroVM. SandboxTenantIDFromContext falls back to the request tenant, which
+// is already the session owner on every non-borrowed path.
+func (m *SessionBoundManager) sessionKey(
+ ctx context.Context,
+ sessionID string,
+) (SessionSandboxKey, error) {
+ tenantID, ok := types.SandboxTenantIDFromContext(ctx)
+ if !ok || tenantID == 0 {
+ return SessionSandboxKey{}, errors.New("sandbox: tenant ID missing from context")
+ }
+ key := SessionSandboxKey{TenantID: tenantID, SessionID: strings.TrimSpace(sessionID)}
+ if err := key.Validate(); err != nil {
+ return SessionSandboxKey{}, err
+ }
+ return key, nil
+}
+
+func (m *SessionBoundManager) remoteDisabled() bool {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ return m.fallback != nil || m.closed
+}
+
+func (m *SessionBoundManager) requireRemoteBackend() error {
+ if m == nil {
+ return ErrSandboxDisabled
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ if m.closed {
+ return ErrSandboxDisabled
+ }
+ if m.fallback != nil {
+ return fmt.Errorf(
+ "sandbox: remote-only capability requires the remote provider (current mode: %s)",
+ m.fallback.Type(),
+ )
+ }
+ return nil
+}
+
+func cleanSessionInputPath(filePath string) (string, error) {
+ clean := path.Clean(strings.TrimSpace(filePath))
+ if clean == SessionInputRoot || strings.HasPrefix(clean, SessionInputRoot+"/") {
+ return clean, nil
+ }
+ return "", fmt.Errorf(
+ "sandbox: session input path %q is outside %s",
+ filePath, SessionInputRoot,
+ )
+}
+
+func cleanSessionWorkDir(workDir string) (string, error) {
+ clean := path.Clean(strings.TrimSpace(workDir))
+ if clean == SessionWorkspaceRoot || strings.HasPrefix(clean, SessionWorkspaceRoot+"/") {
+ return clean, nil
+ }
+ return "", fmt.Errorf(
+ "sandbox: work dir %q is outside %s",
+ workDir, SessionWorkspaceRoot,
+ )
+}
+
+// buildSessionCreateRequest projects Config into a provider-neutral remote
+// create request. The metadata block is populated per-session by the
+// lifecycle coordinator; env vars propagate as-is.
+//
+// The provider parameter (derived from RemoteSandboxClient.Provider()) is the
+// authoritative source of identity — it selects the correct Config fields so
+// Cube and E2B never read each other's templates or TTLs.
+func buildSessionCreateRequest(provider RemoteProvider, cfg *Config) (RemoteCreateRequest, error) {
+ envVars := cloneMetadata(cfg.EnvVars)
+
+ switch provider {
+ case SandboxTypeCube:
+ ttl := cfg.CubeSandboxTTL
+ if ttl <= 0 {
+ ttl = DefaultCubeSandboxTTL
+ }
+ return RemoteCreateRequest{
+ TemplateID: cfg.CubeTemplate,
+ EnvVars: envVars,
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: ttl,
+ Action: RemoteOnTimeoutPause,
+ AutoResume: true,
+ },
+ }, nil
+
+ case SandboxTypeE2B:
+ ttl := cfg.E2BSandboxTTL
+ if ttl <= 0 {
+ ttl = DefaultE2BSandboxTTL
+ }
+ return RemoteCreateRequest{
+ TemplateID: cfg.E2BTemplate,
+ EnvVars: envVars,
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: ttl,
+ Action: RemoteOnTimeoutPause,
+ AutoResume: true,
+ },
+ }, nil
+
+ default:
+ return RemoteCreateRequest{}, fmt.Errorf(
+ "sandbox: unsupported remote provider %q for session create request",
+ provider,
+ )
+ }
+}
+
+// effectiveHTTPTimeout returns the HTTP timeout for health probes and API
+// calls against the provider's control plane. The provider parameter is
+// authoritative: Cube and E2B each read their own timeout field and fall back
+// to their own package-level default.
+func effectiveHTTPTimeout(provider RemoteProvider, cfg *Config) time.Duration {
+ switch provider {
+ case SandboxTypeCube:
+ if cfg.CubeHTTPTimeout > 0 {
+ return cfg.CubeHTTPTimeout
+ }
+ return DefaultCubeHTTPTimeout
+ case SandboxTypeE2B:
+ if cfg.E2BHTTPTimeout > 0 {
+ return cfg.E2BHTTPTimeout
+ }
+ return DefaultE2BHTTPTimeout
+ default:
+ return DefaultCubeHTTPTimeout
+ }
+}
+
+var (
+ _ SessionCapabilityProvider = (*SessionBoundManager)(nil)
+ _ SessionShellExecutor = (*SessionBoundManager)(nil)
+ _ SessionFileStore = (*SessionBoundManager)(nil)
+)
+
+// PermissiveSessionExistenceChecker accepts every session. It is safe in
+// deployments where WeKnora's own DestroySession is the only session-delete
+// path (single-process memory binding store); the Redis-authoritative
+// deployment must inject a real checker consulting the session repository.
+type PermissiveSessionExistenceChecker struct{}
+
+// SessionExists always returns true.
+func (PermissiveSessionExistenceChecker) SessionExists(
+ context.Context, SessionSandboxKey,
+) (bool, error) {
+ return true, nil
+}
diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.go
new file mode 100644
index 000000000..7d0865b4a
--- /dev/null
+++ b/internal/sandbox/session_manager_test.go
@@ -0,0 +1,91 @@
+package sandbox
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func TestExecutionOutputDir(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ cfg *ExecuteConfig
+ want string
+ }{
+ {
+ name: "default when env missing",
+ cfg: &ExecuteConfig{},
+ want: SessionOutputRoot,
+ },
+ {
+ name: "uses env override under workspace",
+ cfg: &ExecuteConfig{
+ Env: map[string]string{
+ skillOutputEnvVar: "/workspace/custom-output",
+ },
+ },
+ want: "/workspace/custom-output",
+ },
+ {
+ name: "rejects path outside workspace",
+ cfg: &ExecuteConfig{
+ Env: map[string]string{
+ skillOutputEnvVar: "/tmp/weknora-skill-output",
+ },
+ },
+ want: SessionOutputRoot,
+ },
+ }
+
+ for _, tt := range tests {
+ tt := tt
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+ require.Equal(t, tt.want, executionOutputDir(tt.cfg))
+ })
+ }
+}
+
+func TestSessionBoundManagerExecuteEnsuresOutputDir(t *testing.T) {
+ client := newFakeRemoteClient(SandboxTypeCube)
+ checker := &fakeSessionExistenceChecker{exists: true}
+ // DefaultConfig carries no Cube template on purpose; the deployment baseline
+ // or the named config supplies it.
+ cfg := DefaultConfig()
+ cfg.CubeTemplate = "tpl-test"
+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
+ Config: cfg,
+ Client: client,
+ Store: NewMemorySessionSandboxBindingStore(),
+ Checker: checker,
+ SkipHealthProbe: true,
+ })
+ require.NoError(t, err)
+
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
+ _, err = mgr.Execute(ctx, &ExecuteConfig{
+ SessionID: "session-a",
+ SkipValidation: true,
+ ScriptContent: "print('ok')\n",
+ Script: "hello.py",
+ Env: map[string]string{
+ skillOutputEnvVar: SessionOutputRoot,
+ },
+ })
+ require.NoError(t, err)
+
+ client.mu.Lock()
+ paths := append([]string(nil), client.makeDirPaths...)
+ execs := append([]RemoteExecRequest(nil), client.execRequests...)
+ client.mu.Unlock()
+ require.Contains(t, paths, SessionOutputRoot)
+ require.NotEmpty(t, execs)
+ require.True(t, execs[0].Shell)
+ require.Contains(t, execs[0].Command, "chown user:user")
+ require.Contains(t, execs[0].Command, SessionOutputRoot)
+}
diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.go
new file mode 100644
index 000000000..24e7892f8
--- /dev/null
+++ b/internal/sandbox/tenant_config.go
@@ -0,0 +1,192 @@
+// Package sandbox: tenant sandbox configuration resolution.
+//
+// ResolveEffectiveConfig turns one stored config into the *Config a manager is
+// built from. A named config is self-contained: provider fields are never
+// inherited from the WEKNORA_SANDBOX_* baseline, they come from the config or
+// they are missing and the config is refused (see config_required.go).
+//
+// Field-level inheritance was tried first and removed. It made the stored row an
+// incomplete picture of where a sandbox actually lives, which broke three things
+// at once: identity comparison had to resolve against the baseline to decide
+// whether an edit stranded anything, editing .env silently re-pointed configs
+// that had left fields blank without cordoning their live sandboxes, and a
+// config whose provider differed from the deployment mode inherited built-in
+// constants instead — quietly dialling 127.0.0.1.
+//
+// What still comes from the baseline is deliberately narrow: the deployment's
+// script execution timeout, which is an operational guardrail rather than part
+// of a backend's identity. A nil tenant config means "the deployment default
+// backend" and yields the baseline unchanged.
+package sandbox
+
+import (
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// ResolveEffectiveConfig returns the Config to build a tenant's sandbox manager
+// from, or an error when the stored config is unsafe (ErrUnsafeOutboundURL) or
+// incomplete (ErrSandboxConfigIncomplete).
+//
+// The overrideX helpers still read as "override" below even though the provider
+// fields were just cleared: they assign only non-empty values, which is exactly
+// what is needed to let an omitted TTL fall through to its built-in default.
+func ResolveEffectiveConfig(
+ tenantCfg *types.TenantSandboxConfig,
+ global *Config,
+) (*Config, error) {
+ if global == nil {
+ return nil, fmt.Errorf("sandbox: global config is required")
+ }
+ effective := *global
+ if tenantCfg == nil {
+ return &effective, nil
+ }
+ // Keep the baseline's cross-cutting settings, drop everything provider
+ // scoped: from here on the stored config is the only source for endpoints,
+ // credentials, domains and templates.
+ clearProviderFields(&effective)
+
+ if tenantCfg.SandboxType != "" {
+ resolved, err := ParseSandboxType(tenantCfg.SandboxType)
+ if err != nil {
+ return nil, err
+ }
+ effective.Type = resolved
+ }
+ overrideSeconds(&effective.DefaultTimeout, tenantCfg.DefaultTimeoutSec)
+ if tenantCfg.EnvVars != nil {
+ effective.EnvVars = cloneMetadata(tenantCfg.EnvVars)
+ }
+ if cube := tenantCfg.Cube; cube != nil {
+ if err := overrideURL(&effective.CubeAPIURL, cube.APIURL); err != nil {
+ return nil, err
+ }
+ if err := overrideURL(&effective.CubeProxyURL, cube.ProxyURL); err != nil {
+ return nil, err
+ }
+ overrideString(&effective.CubeSandboxDomain, cube.SandboxDomain)
+ overrideString(&effective.CubeAPIKey, cube.APIKey)
+ overrideString(&effective.CubeTemplate, cube.TemplateID)
+ overrideSeconds(&effective.CubeHTTPTimeout, cube.HTTPTimeoutSec)
+ overrideSeconds(&effective.CubeSandboxTTL, cube.CubeSandboxTTLSeconds)
+ }
+
+ if e2bCfg := tenantCfg.E2B; e2bCfg != nil {
+ if err := overrideURL(&effective.E2BAPIURL, e2bCfg.APIURL); err != nil {
+ return nil, err
+ }
+ overrideString(&effective.E2BSandboxDomain, e2bCfg.SandboxDomain)
+ overrideString(&effective.E2BAPIKey, e2bCfg.APIKey)
+ overrideString(&effective.E2BTemplate, e2bCfg.TemplateID)
+ overrideSeconds(&effective.E2BHTTPTimeout, e2bCfg.HTTPTimeoutSec)
+ overrideSeconds(&effective.E2BSandboxTTL, e2bCfg.E2BSandboxTTLSeconds)
+ }
+
+ if docker := tenantCfg.Docker; docker != nil {
+ overrideString(&effective.DockerImage, docker.Image)
+ }
+
+ switch effective.Type {
+ case SandboxTypeCube:
+ applyCubeRuntimeDefaults(&effective)
+ case SandboxTypeE2B:
+ applyE2BRuntimeDefaults(&effective)
+ }
+ // Deliberately after the runtime defaults: TTLs and HTTP timeouts have
+ // built-in fallbacks, endpoints and credentials do not.
+ if err := RequireCompleteConfig(&effective); err != nil {
+ return nil, err
+ }
+ return &effective, nil
+}
+
+// clearProviderFields removes every provider-scoped value the deployment
+// baseline carries so a named config cannot silently inherit one. TTLs and HTTP
+// timeouts are cleared too: leaving them empty must fall back to the built-in
+// default rather than to whatever this deployment happens to run, otherwise
+// "inherits nothing" would still have an exception to explain.
+func clearProviderFields(cfg *Config) {
+ cfg.CubeAPIURL = ""
+ cfg.CubeProxyURL = ""
+ cfg.CubeSandboxDomain = ""
+ cfg.CubeAPIKey = ""
+ cfg.CubeTemplate = ""
+ cfg.CubeSandboxTTL = 0
+ cfg.CubeHTTPTimeout = 0
+
+ cfg.E2BAPIURL = ""
+ cfg.E2BSandboxDomain = ""
+ cfg.E2BAPIKey = ""
+ cfg.E2BTemplate = ""
+ cfg.E2BSandboxTTL = 0
+ cfg.E2BHTTPTimeout = 0
+}
+
+// ErrUnsupportedSandboxType marks a sandbox type string we cannot honour. It is
+// a sentinel so callers can classify it as bad input without matching on the
+// message text.
+var ErrUnsupportedSandboxType = errors.New("sandbox: unsupported sandbox type")
+
+// ParseSandboxType maps a stored string onto a SandboxType. Unknown values are
+// rejected so a typo surfaces when the admin saves the config, instead of
+// silently disabling that tenant's sandbox at first use.
+func ParseSandboxType(raw string) (SandboxType, error) {
+ switch SandboxType(raw) {
+ case SandboxTypeCube:
+ return SandboxTypeCube, nil
+ case SandboxTypeE2B:
+ return SandboxTypeE2B, nil
+ case SandboxTypeDocker:
+ return SandboxTypeDocker, nil
+ case SandboxTypeLocal:
+ return SandboxTypeLocal, nil
+ case SandboxTypeDisabled:
+ return SandboxTypeDisabled, nil
+ default:
+ return "", fmt.Errorf("%w %q", ErrUnsupportedSandboxType, raw)
+ }
+}
+
+// EffectiveTemplateID returns the template the given provider will use.
+func EffectiveTemplateID(cfg *Config) string {
+ if cfg == nil {
+ return ""
+ }
+ switch cfg.Type {
+ case SandboxTypeCube:
+ return cfg.CubeTemplate
+ case SandboxTypeE2B:
+ return cfg.E2BTemplate
+ default:
+ return ""
+ }
+}
+
+func overrideString(dst *string, value string) {
+ if value != "" {
+ *dst = value
+ }
+}
+
+// overrideURL is overrideString for endpoint fields: a tenant-supplied URL
+// must pass the SSRF guard before it is accepted into the effective config.
+func overrideURL(dst *string, value string) error {
+ if value == "" {
+ return nil
+ }
+ if err := ValidateOutboundURL(value); err != nil {
+ return err
+ }
+ *dst = value
+ return nil
+}
+
+func overrideSeconds(dst *time.Duration, seconds int) {
+ if seconds > 0 {
+ *dst = time.Duration(seconds) * time.Second
+ }
+}
diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.go
new file mode 100644
index 000000000..630fb3326
--- /dev/null
+++ b/internal/sandbox/tenant_config_test.go
@@ -0,0 +1,196 @@
+package sandbox
+
+import (
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+func globalTestConfig() *Config {
+ return &Config{
+ Type: SandboxTypeE2B,
+ DefaultTimeout: 60 * time.Second,
+ E2BAPIKey: "global-key",
+ E2BAPIURL: "https://global.e2b.dev",
+ E2BSandboxDomain: "global.domain",
+ E2BTemplate: "global-template",
+ E2BSandboxTTL: 10 * time.Minute,
+ E2BHTTPTimeout: 30 * time.Second,
+ }
+}
+
+// completeE2BTenantConfig is the minimum a named E2B config must carry now that
+// nothing is inherited.
+func completeE2BTenantConfig() *types.TenantSandboxConfig {
+ return &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIKey: "tenant-key",
+ TemplateID: "tenant-template",
+ },
+ }
+}
+
+// A nil tenant config means "the deployment default backend", which is the one
+// path where the baseline is used as-is.
+func TestResolveEffectiveConfigNilTenantKeepsGlobal(t *testing.T) {
+ global := globalTestConfig()
+
+ got, err := ResolveEffectiveConfig(nil, global)
+
+ require.NoError(t, err)
+ require.Equal(t, *global, *got)
+}
+
+func TestResolveEffectiveConfigDoesNotMutateGlobal(t *testing.T) {
+ global := globalTestConfig()
+
+ _, err := ResolveEffectiveConfig(completeE2BTenantConfig(), global)
+
+ require.NoError(t, err)
+ require.Equal(t, "global-key", global.E2BAPIKey,
+ "resolution must not leak tenant values into the shared global config")
+}
+
+// The point of the whole design: a named config never picks up the deployment's
+// endpoint, domain or key, so what it does not state it does not get.
+func TestResolveEffectiveConfigDoesNotInheritProviderFields(t *testing.T) {
+ global := globalTestConfig()
+
+ got, err := ResolveEffectiveConfig(completeE2BTenantConfig(), global)
+
+ require.NoError(t, err)
+ require.Equal(t, "tenant-key", got.E2BAPIKey)
+ require.Equal(t, "tenant-template", got.E2BTemplate)
+ require.Empty(t, got.E2BAPIURL, "go-e2b resolves its own API base when unset")
+ require.Empty(t, got.E2BSandboxDomain)
+}
+
+// A leftover sub-struct from the deployment's other provider must not survive
+// either, or a cube config would silently answer with e2b coordinates.
+func TestResolveEffectiveConfigClearsInactiveProviderBaseline(t *testing.T) {
+ global := globalTestConfig() // global is e2b, with e2b credentials set
+
+ got, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{
+ APIKey: "cube-key", APIURL: "https://203.0.113.20",
+ ProxyURL: "https://203.0.113.21", SandboxDomain: "cube.example",
+ TemplateID: "cube-template",
+ },
+ }, global)
+
+ require.NoError(t, err)
+ require.Equal(t, SandboxTypeCube, got.Type)
+ require.Equal(t, "https://203.0.113.20", got.CubeAPIURL)
+ require.Empty(t, got.E2BAPIKey, "the baseline's e2b credentials must not ride along")
+ require.Empty(t, got.E2BTemplate)
+}
+
+func TestResolveEffectiveConfigRejectsIncompleteCube(t *testing.T) {
+ _, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{APIURL: "https://203.0.113.20"},
+ }, globalTestConfig())
+
+ require.ErrorIs(t, err, ErrSandboxConfigIncomplete)
+ require.Contains(t, err.Error(), "proxy_url")
+ require.Contains(t, err.Error(), "sandbox_domain")
+ require.Contains(t, err.Error(), "template_id")
+}
+
+func TestResolveEffectiveConfigRejectsIncompleteE2B(t *testing.T) {
+ _, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{TemplateID: "t1"},
+ }, globalTestConfig())
+
+ require.ErrorIs(t, err, ErrSandboxConfigIncomplete)
+ require.Contains(t, err.Error(), "api_key")
+}
+
+func TestResolveEffectiveConfigAppliesTimeoutsAndTTL(t *testing.T) {
+ global := globalTestConfig()
+ tenantCfg := completeE2BTenantConfig()
+ tenantCfg.DefaultTimeoutSec = 90
+ tenantCfg.E2B.HTTPTimeoutSec = 15
+ tenantCfg.E2B.E2BSandboxTTLSeconds = 600
+
+ got, err := ResolveEffectiveConfig(tenantCfg, global)
+
+ require.NoError(t, err)
+ require.Equal(t, 90*time.Second, got.DefaultTimeout)
+ require.Equal(t, 15*time.Second, got.E2BHTTPTimeout)
+ require.Equal(t, 600*time.Second, got.E2BSandboxTTL)
+}
+
+// Tuning fields fall back to the built-in constants, never to the deployment's:
+// "inherits nothing" would be a much weaker rule with an exception here.
+func TestResolveEffectiveConfigTuningFallsBackToBuiltIns(t *testing.T) {
+ global := globalTestConfig()
+ global.E2BSandboxTTL = 10 * time.Minute
+ global.E2BHTTPTimeout = 90 * time.Second
+
+ got, err := ResolveEffectiveConfig(completeE2BTenantConfig(), global)
+
+ require.NoError(t, err)
+ require.Equal(t, DefaultE2BSandboxTTL, got.E2BSandboxTTL)
+ require.Equal(t, DefaultE2BHTTPTimeout, got.E2BHTTPTimeout)
+ require.Equal(t, global.DefaultTimeout, got.DefaultTimeout,
+ "the execution timeout is deployment policy and does carry over")
+}
+
+func TestResolveEffectiveConfigDisabled(t *testing.T) {
+ tenantCfg := &types.TenantSandboxConfig{SandboxType: "disabled"}
+
+ got, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
+
+ require.NoError(t, err)
+ require.Equal(t, SandboxTypeDisabled, got.Type)
+}
+
+func TestResolveEffectiveConfigRejectsUnknownType(t *testing.T) {
+ tenantCfg := &types.TenantSandboxConfig{SandboxType: "quantum"}
+
+ _, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
+
+ require.Error(t, err)
+}
+
+func TestResolveEffectiveConfigRejectsUnsafeURL(t *testing.T) {
+ tenantCfg := &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{APIURL: "http://169.254.169.254"},
+ }
+
+ _, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
+
+ require.ErrorIs(t, err, ErrUnsafeOutboundURL)
+}
+
+func TestResolveEffectiveConfigRejectsUnsafeCubeProxyURL(t *testing.T) {
+ tenantCfg := &types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{
+ APIURL: "https://203.0.113.10",
+ ProxyURL: "http://127.0.0.1:80",
+ },
+ }
+
+ _, err := ResolveEffectiveConfig(tenantCfg, globalTestConfig())
+
+ require.ErrorIs(t, err, ErrUnsafeOutboundURL)
+}
+
+func TestEffectiveTemplateIDPerProvider(t *testing.T) {
+ require.Equal(t, "e2b-tpl", EffectiveTemplateID(&Config{
+ Type: SandboxTypeE2B, E2BTemplate: "e2b-tpl", CubeTemplate: "cube-tpl",
+ }))
+ require.Equal(t, "cube-tpl", EffectiveTemplateID(&Config{
+ Type: SandboxTypeCube, E2BTemplate: "e2b-tpl", CubeTemplate: "cube-tpl",
+ }))
+ require.Empty(t, EffectiveTemplateID(&Config{Type: SandboxTypeLocal}))
+ require.Empty(t, EffectiveTemplateID(nil))
+}
diff --git a/internal/sandbox/tenant_resolver.go b/internal/sandbox/tenant_resolver.go
new file mode 100644
index 000000000..1bcfd5249
--- /dev/null
+++ b/internal/sandbox/tenant_resolver.go
@@ -0,0 +1,226 @@
+// Package sandbox: per-config sandbox manager resolution.
+//
+// A manager is built for one (tenant, sandbox config) pair — a workspace holds
+// several named configs and each agent selects one. Managers are built per
+// request and deliberately NOT cached, mirroring modelService, which rebuilds
+// model clients on every call (see internal/application/service/model.go).
+//
+// Caching was considered and rejected after checking what SessionBoundManager
+// actually holds:
+//
+// - remoteSessionLifecycle has no mutex; create/recover serialization lives
+// entirely in the shared binding store (Redis SET NX, or the in-memory
+// store's own lock), and that store is injected, so it stays a singleton
+// either way.
+// - SessionBoundManager.mu guards only the Cleanup idempotency flag.
+// - No handles are held across requests: Execute re-Connects every time.
+//
+// That left the construction-time Health probe as the only real cost, which
+// SkipHealthProbe removes. Connection reuse is preserved by sharing one
+// http.Transport across tenants (Cube additionally routes its data plane
+// through CubeTransportPool; see cube_transport.go). The upshot: no cache, no
+// eviction, no invalidation plumbing, and a config change takes effect on the
+// next request.
+package sandbox
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// ErrSandboxConfigNotFound means the referenced config is gone (deleted, or
+// never existed). Callers must surface it rather than degrade to the default
+// backend: running an agent's scripts on a backend it was not pointed at is a
+// silent, security-relevant substitution.
+var ErrSandboxConfigNotFound = errors.New("sandbox: config not found")
+
+// ErrSandboxConfigCordoned means the config's identity fields are mid-change.
+// It is transient by construction (the cordon is a short lease), so callers
+// should surface it as retriable.
+var ErrSandboxConfigCordoned = errors.New("sandbox: config is being updated")
+
+// ResolvedTenantSandboxConfig is what the loader reports about one config.
+type ResolvedTenantSandboxConfig struct {
+ // Config is nil when configID was empty (use the global default).
+ Config *types.TenantSandboxConfig
+
+ // Found is false when a non-empty configID matched no row.
+ Found bool
+
+ // Cordoned is true while the config's credentials are being replaced.
+ Cordoned bool
+}
+
+// TenantSandboxConfigLoader fetches one stored sandbox config.
+// Implemented in the application layer so this package stays free of
+// repository dependencies.
+type TenantSandboxConfigLoader interface {
+ Load(ctx context.Context, tenantID uint64, configID string) (ResolvedTenantSandboxConfig, error)
+}
+
+// TenantSandboxResolver produces the Manager for a (tenant, config) pair.
+type TenantSandboxResolver interface {
+ // Resolve builds the manager for configID. An empty configID selects the
+ // deployment-wide default manager.
+ Resolve(ctx context.Context, tenantID uint64, configID string) (Manager, error)
+}
+
+// TenantSandboxResolverDeps bundles the resolver's wiring.
+type TenantSandboxResolverDeps struct {
+ // GlobalConfig is the process-wide config built from WEKNORA_SANDBOX_*.
+ GlobalConfig *Config
+
+ // DefaultManager serves tenants without their own configuration, which
+ // preserves the pre-feature behaviour for existing deployments.
+ DefaultManager Manager
+
+ Loader TenantSandboxConfigLoader
+ Store SessionSandboxBindingStore
+ Checker SessionExistenceChecker
+
+ // SharedTransport is reused by every tenant's HTTP client. Optional; a
+ // guarded transport is installed when nil.
+ SharedTransport *http.Transport
+}
+
+type tenantSandboxResolver struct {
+ deps TenantSandboxResolverDeps
+ transport *http.Transport
+
+ // cubeTransports must outlive the per-request clients it serves, which is
+ // the whole point of holding it here rather than building it per Resolve.
+ cubeTransports *CubeTransportPool
+}
+
+// NewTenantSandboxResolver validates the wiring and returns a resolver.
+func NewTenantSandboxResolver(deps TenantSandboxResolverDeps) (TenantSandboxResolver, error) {
+ if deps.GlobalConfig == nil {
+ return nil, errors.New("sandbox: tenant resolver requires a global config")
+ }
+ if deps.Loader == nil {
+ return nil, errors.New("sandbox: tenant resolver requires a config loader")
+ }
+ if deps.Store == nil {
+ return nil, errors.New("sandbox: tenant resolver requires a binding store")
+ }
+ if deps.Checker == nil {
+ return nil, errors.New("sandbox: tenant resolver requires a session checker")
+ }
+ transport := deps.SharedTransport
+ if transport == nil {
+ transport = NewGuardedTransport()
+ }
+ return &tenantSandboxResolver{
+ deps: deps,
+ transport: transport,
+ cubeTransports: NewCubeTransportPool(transport),
+ }, nil
+}
+
+// NewGuardedTransport returns an http.Transport whose dialer refuses addresses
+// the outbound policy forbids. This closes the DNS-rebinding window that
+// save-time URL validation cannot cover.
+func NewGuardedTransport() *http.Transport {
+ return &http.Transport{
+ DialContext: (&net.Dialer{
+ Timeout: 10 * time.Second,
+ KeepAlive: 30 * time.Second,
+ Control: SafeDialControl,
+ }).DialContext,
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 4,
+ IdleConnTimeout: 90 * time.Second,
+ }
+}
+
+// Resolve builds the manager from the selected config's current settings.
+func (r *tenantSandboxResolver) Resolve(
+ ctx context.Context,
+ tenantID uint64,
+ configID string,
+) (Manager, error) {
+ if strings.TrimSpace(configID) == "" ||
+ configID == types.SandboxConfigIDGlobalDefault {
+ return r.deps.DefaultManager, nil
+ }
+
+ resolved, err := r.deps.Loader.Load(ctx, tenantID, configID)
+ if err != nil {
+ return nil, fmt.Errorf(
+ "sandbox: load workspace %d config %q: %w", tenantID, configID, err)
+ }
+ if !resolved.Found {
+ return nil, fmt.Errorf("%w: %s", ErrSandboxConfigNotFound, configID)
+ }
+ if resolved.Cordoned {
+ return nil, fmt.Errorf("%w: %s", ErrSandboxConfigCordoned, configID)
+ }
+
+ effective, err := ResolveEffectiveConfig(resolved.Config, r.deps.GlobalConfig)
+ if err != nil {
+ return nil, err
+ }
+
+ switch effective.Type {
+ case SandboxTypeDisabled:
+ return NewDisabledManager(), nil
+ case SandboxTypeCube, SandboxTypeE2B:
+ client, err := r.buildClient(effective)
+ if err != nil {
+ return nil, err
+ }
+ return NewSessionBoundManager(SessionBoundManagerConfig{
+ Config: effective,
+ Client: client,
+ Store: r.deps.Store,
+ Checker: r.deps.Checker,
+ SkipHealthProbe: true,
+ ConfigID: configID,
+ })
+ default:
+ // docker/local have no per-config remote wiring.
+ return r.deps.DefaultManager, nil
+ }
+}
+
+// buildClient constructs the provider adapter for this tenant, injecting the
+// shared transport so pooling survives per-request construction.
+func (r *tenantSandboxResolver) buildClient(cfg *Config) (RemoteSandboxClient, error) {
+ switch cfg.Type {
+ case SandboxTypeCube:
+ return NewCubeRemoteClientWithPool(cfg, r.cubeTransports)
+ case SandboxTypeE2B:
+ return NewE2BRemoteClientWithTransport(cfg, r.transport)
+ default:
+ return nil, fmt.Errorf("sandbox: provider %q has no remote client", cfg.Type)
+ }
+}
+
+// NewRemoteClientForCheck builds a throwaway client for connectivity probes.
+// It is never cached and never handed to a manager.
+//
+// Both providers get a guarded transport. The endpoints being probed come
+// straight off an admin's unsaved form, so save-time ValidateOutboundURL has
+// not necessarily run against the address this client will actually dial, and
+// even when it has, a hostname can resolve to a public address during
+// validation and to 169.254.169.254 at dial time.
+func NewRemoteClientForCheck(cfg *Config) (RemoteSandboxClient, error) {
+ if cfg == nil {
+ return nil, errors.New("sandbox: config is required")
+ }
+ switch cfg.Type {
+ case SandboxTypeCube:
+ return NewCubeRemoteClientWithPool(cfg, NewCubeTransportPool(nil))
+ case SandboxTypeE2B:
+ return NewE2BRemoteClientWithTransport(cfg, NewGuardedTransport())
+ 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.go
new file mode 100644
index 000000000..ffa6d5553
--- /dev/null
+++ b/internal/sandbox/tenant_resolver_test.go
@@ -0,0 +1,129 @@
+package sandbox
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+type stubTenantConfigLoader struct {
+ result ResolvedTenantSandboxConfig
+ hits int
+}
+
+func (s *stubTenantConfigLoader) Load(
+ context.Context, uint64, string,
+) (ResolvedTenantSandboxConfig, error) {
+ s.hits++
+ return s.result, nil
+}
+
+func newTestResolver(t *testing.T, loader TenantSandboxConfigLoader) (TenantSandboxResolver, Manager) {
+ t.Helper()
+ fallback := NewDisabledManager()
+ resolver, err := NewTenantSandboxResolver(TenantSandboxResolverDeps{
+ GlobalConfig: &Config{
+ Type: SandboxTypeE2B,
+ DefaultTimeout: 60 * time.Second,
+ E2BAPIKey: "global-key",
+ E2BAPIURL: "https://203.0.113.30",
+ E2BTemplate: "global-template",
+ E2BSandboxTTL: time.Minute,
+ E2BHTTPTimeout: 30 * time.Second,
+ },
+ DefaultManager: fallback,
+ Loader: loader,
+ Store: NewMemorySessionSandboxBindingStore(),
+ Checker: PermissiveSessionExistenceChecker{},
+ })
+ require.NoError(t, err)
+ return resolver, fallback
+}
+
+// Existing deployments have no tenant config at all; they must keep using the
+// process-wide manager built from WEKNORA_SANDBOX_*.
+func TestResolveEmptyConfigIDUsesDefaultManager(t *testing.T) {
+ resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{})
+
+ mgr, err := resolver.Resolve(context.Background(), 42, "")
+
+ require.NoError(t, err)
+ require.Same(t, fallback, mgr)
+}
+
+// A cordoned config must not produce a manager: the whole point of the cordon
+// is that no new sandbox may be created on credentials about to be replaced.
+func TestResolveRefusesCordonedConfig(t *testing.T) {
+ resolver, _ := newTestResolver(t, &stubTenantConfigLoader{
+ result: ResolvedTenantSandboxConfig{Found: true, Cordoned: true},
+ })
+
+ mgr, err := resolver.Resolve(context.Background(), 7, "cfg-a")
+
+ require.Nil(t, mgr)
+ require.ErrorIs(t, err, ErrSandboxConfigCordoned)
+}
+
+// A missing config must fail loudly. Falling back to the global default would
+// silently run the agent on a DIFFERENT backend than the one it was pointed at.
+func TestResolveRefusesMissingConfig(t *testing.T) {
+ resolver, _ := newTestResolver(t, &stubTenantConfigLoader{
+ result: ResolvedTenantSandboxConfig{Found: false},
+ })
+
+ mgr, err := resolver.Resolve(context.Background(), 7, "cfg-gone")
+
+ require.Nil(t, mgr)
+ require.ErrorIs(t, err, ErrSandboxConfigNotFound)
+}
+
+// Construction must not perform a Health round-trip (it happens per request),
+// and skipping it must also skip the silent fallback to LocalSandbox: a tenant
+// that chose E2B should never have scripts quietly run as a local process.
+func TestResolveBuildsRemoteManagerWithoutHealthProbe(t *testing.T) {
+ resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{
+ result: ResolvedTenantSandboxConfig{
+ Config: &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIKey: "tenant-key", TemplateID: "tenant-template",
+ },
+ },
+ Found: true,
+ },
+ })
+
+ mgr, err := resolver.Resolve(context.Background(), 42, "cfg-a")
+
+ require.NoError(t, err)
+ require.NotSame(t, fallback, mgr)
+ require.Equal(t, SandboxTypeE2B, mgr.GetType())
+}
+
+// No caching: the loader is consulted on every Resolve, which is what makes a
+// config change take effect on the next request with no invalidation step.
+func TestResolveBuildsFreshManagerEveryCall(t *testing.T) {
+ loader := &stubTenantConfigLoader{
+ result: ResolvedTenantSandboxConfig{
+ Config: &types.TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &types.E2BSandboxConfig{
+ APIKey: "tenant-key", TemplateID: "tenant-template",
+ },
+ },
+ Found: true,
+ },
+ }
+ resolver, _ := newTestResolver(t, loader)
+
+ first, err := resolver.Resolve(context.Background(), 42, "cfg-a")
+ require.NoError(t, err)
+ second, err := resolver.Resolve(context.Background(), 42, "cfg-a")
+ require.NoError(t, err)
+
+ require.NotSame(t, first, second)
+ require.Equal(t, 2, loader.hits)
+}
diff --git a/internal/sandbox/url_guard.go b/internal/sandbox/url_guard.go
new file mode 100644
index 000000000..8ffa6cd70
--- /dev/null
+++ b/internal/sandbox/url_guard.go
@@ -0,0 +1,181 @@
+// Package sandbox: outbound URL guard for tenant-supplied endpoints.
+//
+// Tenants configure their own sandbox control-plane URLs and the server dials
+// them. Without a guard that is a Server-Side Request Forgery primitive: the
+// most damaging target is the cloud metadata service (169.254.169.254), which
+// hands out instance credentials, followed by any internal service reachable
+// from the application host.
+//
+// Defence is two-layered on purpose:
+//
+// - Validate runs when a config is saved or probed, giving the admin an
+// immediate, readable error.
+// - DialControl runs at connect time on every request. This is the layer
+// that actually holds, because a hostname can resolve to a public address
+// during validation and to 169.254.169.254 at dial time (DNS rebinding).
+//
+// Self-hosted deployments complicate this: CubeAPI's own default endpoint is
+// http://127.0.0.1:33000, so a blanket ban on private addresses would make
+// per-tenant Cube configuration impossible. The policy is therefore
+// deny-by-default with an explicit operator opt-in
+// (WEKNORA_SANDBOX_ALLOW_PRIVATE_ENDPOINTS=true). Even when opted in, the
+// link-local range — and with it the cloud metadata address — stays blocked,
+// because it is never a legitimate sandbox endpoint.
+package sandbox
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+// ErrUnsafeOutboundURL is returned for any endpoint that uses an unsupported
+// scheme or resolves to an address the policy forbids.
+var ErrUnsafeOutboundURL = errors.New("sandbox: unsafe outbound URL")
+
+// AllowPrivateEndpointsEnv opts a deployment into private/loopback sandbox
+// endpoints. Required for self-hosted Cube, which listens on 127.0.0.1 by
+// default. Link-local addresses remain blocked regardless.
+const AllowPrivateEndpointsEnv = "WEKNORA_SANDBOX_ALLOW_PRIVATE_ENDPOINTS"
+
+// OutboundURLPolicy decides which addresses tenant-supplied endpoints may
+// resolve to.
+type OutboundURLPolicy struct {
+ // AllowPrivate permits loopback and RFC1918 addresses. It never permits
+ // link-local (169.254.0.0/16), which carries the cloud metadata service.
+ AllowPrivate bool
+}
+
+// DefaultOutboundURLPolicy reads the policy from the environment. Absent or
+// unparseable values fail closed.
+func DefaultOutboundURLPolicy() OutboundURLPolicy {
+ allow, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(AllowPrivateEndpointsEnv)))
+ if err != nil {
+ allow = false
+ }
+ return OutboundURLPolicy{AllowPrivate: allow}
+}
+
+// ValidateOutboundURL checks raw against the environment's policy.
+func ValidateOutboundURL(raw string) error {
+ return DefaultOutboundURLPolicy().Validate(raw)
+}
+
+// SafeDialControl is a net.Dialer.Control hook using the environment's policy.
+func SafeDialControl(network string, address string, conn syscall.RawConn) error {
+ return DefaultOutboundURLPolicy().DialControl(network, address, conn)
+}
+
+// Validate reports whether raw is an acceptable tenant-supplied endpoint. It
+// rejects non-HTTP schemes and any host that resolves to a forbidden address.
+//
+// Callers must ALSO install DialControl on the dialer they use; Validate alone
+// cannot close the DNS-rebinding window.
+func (p OutboundURLPolicy) Validate(raw string) error {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return fmt.Errorf("%w: empty URL", ErrUnsafeOutboundURL)
+ }
+ parsed, err := url.Parse(raw)
+ if err != nil {
+ return fmt.Errorf("%w: %v", ErrUnsafeOutboundURL, err)
+ }
+ switch strings.ToLower(parsed.Scheme) {
+ case "http", "https":
+ default:
+ return fmt.Errorf("%w: scheme %q is not allowed", ErrUnsafeOutboundURL, parsed.Scheme)
+ }
+
+ host := parsed.Hostname()
+ if host == "" {
+ return fmt.Errorf("%w: missing host", ErrUnsafeOutboundURL)
+ }
+ // ".local" is mDNS; "localhost" is only acceptable under the opt-in.
+ lower := strings.ToLower(host)
+ if strings.HasSuffix(lower, ".local") {
+ return fmt.Errorf("%w: host %q is mDNS-local", ErrUnsafeOutboundURL, host)
+ }
+ if lower == "localhost" || strings.HasSuffix(lower, ".localhost") {
+ if !p.AllowPrivate {
+ return fmt.Errorf(
+ "%w: host %q is loopback; set %s=true to allow self-hosted endpoints",
+ ErrUnsafeOutboundURL, host, AllowPrivateEndpointsEnv,
+ )
+ }
+ return nil
+ }
+
+ // A literal IP is checked directly; a hostname has every resolved address
+ // checked, since one acceptable answer does not make the rest safe.
+ if ip := net.ParseIP(host); ip != nil {
+ return p.checkIP(ip)
+ }
+ addrs, err := net.LookupIP(host)
+ if err != nil {
+ return fmt.Errorf("%w: cannot resolve %q: %v", ErrUnsafeOutboundURL, host, err)
+ }
+ for _, ip := range addrs {
+ if err := p.checkIP(ip); err != nil {
+ return fmt.Errorf("%w: host %q resolves to %s", ErrUnsafeOutboundURL, host, ip)
+ }
+ }
+ return nil
+}
+
+// DialControl refuses connections to forbidden addresses. It inspects the
+// concrete address the kernel is about to connect to, which is what makes it
+// immune to DNS rebinding.
+func (p OutboundURLPolicy) DialControl(_ string, address string, _ syscall.RawConn) error {
+ host, _, err := net.SplitHostPort(address)
+ if err != nil {
+ return fmt.Errorf("%w: cannot parse dial address %q", ErrUnsafeOutboundURL, address)
+ }
+ ip := net.ParseIP(host)
+ if ip == nil {
+ return fmt.Errorf("%w: dial address %q is not an IP", ErrUnsafeOutboundURL, host)
+ }
+ if err := p.checkIP(ip); err != nil {
+ return err
+ }
+ return nil
+}
+
+// checkIP applies the policy to a concrete address.
+func (p OutboundURLPolicy) checkIP(ip net.IP) error {
+ if ip == nil {
+ return fmt.Errorf("%w: missing address", ErrUnsafeOutboundURL)
+ }
+ // Never allowed, even under the private opt-in: link-local carries the
+ // cloud metadata service, and multicast/unspecified are meaningless here.
+ if ip.IsUnspecified() ||
+ ip.IsLinkLocalUnicast() ||
+ ip.IsLinkLocalMulticast() ||
+ ip.IsInterfaceLocalMulticast() ||
+ ip.IsMulticast() {
+ return fmt.Errorf("%w: address %s is never routable to a sandbox", ErrUnsafeOutboundURL, ip)
+ }
+ if ip.IsLoopback() || ip.IsPrivate() || isCarrierGradeNAT(ip) {
+ if !p.AllowPrivate {
+ return fmt.Errorf(
+ "%w: address %s is private; set %s=true to allow self-hosted endpoints",
+ ErrUnsafeOutboundURL, ip, AllowPrivateEndpointsEnv,
+ )
+ }
+ }
+ return nil
+}
+
+// isCarrierGradeNAT reports whether ip falls in 100.64.0.0/10, which IsPrivate
+// does not cover but which is equally unsuitable as a public endpoint.
+func isCarrierGradeNAT(ip net.IP) bool {
+ v4 := ip.To4()
+ if v4 == nil {
+ return false
+ }
+ return v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127
+}
diff --git a/internal/sandbox/url_guard_test.go b/internal/sandbox/url_guard_test.go
new file mode 100644
index 000000000..8325e4f4b
--- /dev/null
+++ b/internal/sandbox/url_guard_test.go
@@ -0,0 +1,152 @@
+package sandbox
+
+import (
+ "errors"
+ "net"
+ "testing"
+)
+
+// denyPrivate is the secure default policy.
+var denyPrivate = OutboundURLPolicy{AllowPrivate: false}
+
+// allowPrivate is the self-hosted opt-in policy.
+var allowPrivate = OutboundURLPolicy{AllowPrivate: true}
+
+func TestPolicyRejectsAlwaysForbiddenTargets(t *testing.T) {
+ // These must be rejected under BOTH policies: link-local carries the cloud
+ // metadata service, and the rest are not routable to a sandbox.
+ cases := []struct{ name, raw string }{
+ {"cloud metadata", "http://169.254.169.254/latest/meta-data/"},
+ {"link local", "http://169.254.1.1"},
+ {"unspecified", "http://0.0.0.0"},
+ {"mdns suffix", "http://cube.local"},
+ {"bad scheme file", "file:///etc/passwd"},
+ {"bad scheme gopher", "gopher://evil"},
+ {"empty", ""},
+ {"no host", "http://"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ for label, policy := range map[string]OutboundURLPolicy{
+ "deny-private": denyPrivate,
+ "allow-private": allowPrivate,
+ } {
+ err := policy.Validate(tc.raw)
+ if err == nil {
+ t.Fatalf("[%s] Validate(%q) = nil, want error", label, tc.raw)
+ }
+ if !errors.Is(err, ErrUnsafeOutboundURL) {
+ t.Fatalf("[%s] Validate(%q) error = %v, want ErrUnsafeOutboundURL",
+ label, tc.raw, err)
+ }
+ }
+ })
+ }
+}
+
+func TestPolicyRejectsPrivateTargetsByDefault(t *testing.T) {
+ for _, raw := range []string{
+ "http://127.0.0.1:8080",
+ "http://localhost:8080",
+ "http://[::1]:8080",
+ "http://10.0.0.5",
+ "http://172.16.3.4",
+ "http://192.168.1.1",
+ "http://100.64.0.1",
+ } {
+ if err := denyPrivate.Validate(raw); err == nil {
+ t.Fatalf("denyPrivate.Validate(%q) = nil, want error", raw)
+ }
+ }
+}
+
+func TestPolicyAllowsPrivateTargetsWhenOptedIn(t *testing.T) {
+ // Self-hosted Cube listens on 127.0.0.1:33000 by default, so this opt-in
+ // is what makes per-tenant Cube configuration possible at all.
+ for _, raw := range []string{
+ "http://127.0.0.1:33000",
+ "http://localhost:33000",
+ "http://10.0.0.5",
+ "http://192.168.1.1:80",
+ } {
+ if err := allowPrivate.Validate(raw); err != nil {
+ t.Fatalf("allowPrivate.Validate(%q) = %v, want nil", raw, err)
+ }
+ }
+}
+
+func TestPolicyAllowsPublicLiteralAddresses(t *testing.T) {
+ // Literal addresses keep this hermetic: no DNS required.
+ for _, raw := range []string{
+ "http://203.0.113.10:8080",
+ "https://203.0.113.10",
+ "https://[2001:db8::1]:443/v1",
+ } {
+ if err := denyPrivate.Validate(raw); err != nil {
+ t.Fatalf("denyPrivate.Validate(%q) = %v, want nil", raw, err)
+ }
+ }
+}
+
+func TestPolicyAllowsPublicHostname(t *testing.T) {
+ const host = "api.e2b.dev"
+ if _, err := net.LookupIP(host); err != nil {
+ t.Skipf("no DNS available in this environment: %v", err)
+ }
+ if err := denyPrivate.Validate("https://" + host); err != nil {
+ t.Fatalf("denyPrivate.Validate(%q) = %v, want nil", host, err)
+ }
+}
+
+func TestPolicyValidateRejectsUnresolvableHost(t *testing.T) {
+ // Fail closed: if we cannot verify where a host points, we refuse it. This
+ // also gives the admin an early "that hostname does not exist" signal.
+ err := denyPrivate.Validate("https://this-host-does-not-exist.invalid")
+ if err == nil {
+ t.Fatal("Validate on an unresolvable host = nil, want error")
+ }
+}
+
+func TestPolicyDialControlMirrorsValidation(t *testing.T) {
+ // The dialer must forbid exactly what validation forbids, otherwise a
+ // saved config would fail mysteriously at first use.
+ alwaysBlocked := []string{"169.254.169.254:80", "0.0.0.0:80"}
+ privateOnly := []string{"127.0.0.1:8080", "10.1.2.3:443", "[::1]:8080"}
+
+ for _, address := range alwaysBlocked {
+ if err := denyPrivate.DialControl("tcp", address, nil); err == nil {
+ t.Fatalf("denyPrivate.DialControl(%q) = nil, want error", address)
+ }
+ if err := allowPrivate.DialControl("tcp", address, nil); err == nil {
+ t.Fatalf("allowPrivate.DialControl(%q) = nil, want error", address)
+ }
+ }
+ for _, address := range privateOnly {
+ if err := denyPrivate.DialControl("tcp", address, nil); err == nil {
+ t.Fatalf("denyPrivate.DialControl(%q) = nil, want error", address)
+ }
+ if err := allowPrivate.DialControl("tcp", address, nil); err != nil {
+ t.Fatalf("allowPrivate.DialControl(%q) = %v, want nil", address, err)
+ }
+ }
+ for _, address := range []string{"203.0.113.10:443", "[2001:db8::1]:443"} {
+ if err := denyPrivate.DialControl("tcp", address, nil); err != nil {
+ t.Fatalf("denyPrivate.DialControl(%q) = %v, want nil", address, err)
+ }
+ }
+}
+
+func TestDefaultOutboundURLPolicyFailsClosed(t *testing.T) {
+ t.Setenv(AllowPrivateEndpointsEnv, "")
+ if DefaultOutboundURLPolicy().AllowPrivate {
+ t.Fatal("an unset opt-in must fail closed")
+ }
+ t.Setenv(AllowPrivateEndpointsEnv, "not-a-bool")
+ if DefaultOutboundURLPolicy().AllowPrivate {
+ t.Fatal("an unparseable opt-in must fail closed")
+ }
+ t.Setenv(AllowPrivateEndpointsEnv, "true")
+ if !DefaultOutboundURLPolicy().AllowPrivate {
+ t.Fatal("an explicit true must enable private endpoints")
+ }
+}
diff --git a/internal/sandbox/validator_test.go b/internal/sandbox/validator_test.go
index a8fd3a944..67b461559 100644
--- a/internal/sandbox/validator_test.go
+++ b/internal/sandbox/validator_test.go
@@ -364,7 +364,7 @@ func BenchmarkValidateArgs(b *testing.B) {
v := NewScriptValidator()
args := []string{"--input", "file.txt", "--name", "report 2024", "--out", "/tmp/x", "--verbose", "--limit=50"}
b.ReportAllocs()
- for i := 0; i < b.N; i++ {
+ for b.Loop() {
_ = v.ValidateArgs(args)
}
}
diff --git a/internal/types/agent.go b/internal/types/agent.go
index d14a154da..8132a381d 100644
--- a/internal/types/agent.go
+++ b/internal/types/agent.go
@@ -52,7 +52,8 @@ type AgentConfig struct {
AllowedSkills []string `json:"allowed_skills"` // Skill names whitelist (empty = allow all)
// Runtime-only fields (not persisted)
- VLMModelID string `json:"-"` // VLM model ID for tool result image analysis (set from CustomAgent config)
+ VLMModelID string `json:"-"` // VLM model ID for tool result image analysis (set from CustomAgent config)
+ SandboxConfigID string `json:"-"` // Workspace sandbox config ID for skill execution (set from CustomAgent config)
// Per-request @mention pins (runtime only; injected as <must_use> in the user message).
PinnedMCPServiceIDs []string `json:"-"`
PinnedSkillNames []string `json:"-"`
diff --git a/internal/types/config_redaction.go b/internal/types/config_redaction.go
index 233899805..5636961a4 100644
--- a/internal/types/config_redaction.go
+++ b/internal/types/config_redaction.go
@@ -263,3 +263,88 @@ func MergeStorageEngineConfigForUpdate(incoming, existing *StorageEngineConfig)
}
return &out
}
+
+// SandboxConfigForResponse returns a copy of cfg safe to serialize into an API
+// response. When maskSecrets is true every secret-bearing field is replaced
+// with RedactedSecretPlaceholder. Unset secrets stay empty so the UI can tell
+// "configured" apart from "not configured".
+func SandboxConfigForResponse(cfg *TenantSandboxConfig, maskSecrets bool) *TenantSandboxConfig {
+ if cfg == nil {
+ return nil
+ }
+ out := *cfg
+ if !maskSecrets {
+ return &out
+ }
+ if out.Cube != nil {
+ cube := *out.Cube
+ if cube.APIKey != "" {
+ cube.APIKey = RedactedSecretPlaceholder
+ }
+ out.Cube = &cube
+ }
+ if out.E2B != nil {
+ e2b := *out.E2B
+ if e2b.APIKey != "" {
+ e2b.APIKey = RedactedSecretPlaceholder
+ }
+ out.E2B = &e2b
+ }
+ // EnvVars values are encrypted at rest and may hold credentials, so they
+ // are masked as a class rather than by name.
+ if len(out.EnvVars) > 0 {
+ envVars := make(map[string]string, len(out.EnvVars))
+ for name, value := range out.EnvVars {
+ if value != "" {
+ value = RedactedSecretPlaceholder
+ }
+ envVars[name] = value
+ }
+ out.EnvVars = envVars
+ }
+ return &out
+}
+
+// MergeSandboxConfigForUpdate resolves redacted placeholders in incoming
+// against the currently stored config, so a client that never received the
+// real secret can submit the rest of the form without wiping it.
+func MergeSandboxConfigForUpdate(incoming, existing *TenantSandboxConfig) *TenantSandboxConfig {
+ if incoming == nil {
+ return nil
+ }
+ out := *incoming
+
+ if out.Cube != nil {
+ cube := *out.Cube
+ var prev CubeSandboxConfig
+ if existing != nil && existing.Cube != nil {
+ prev = *existing.Cube
+ }
+ cube.APIKey = PreserveIfRedacted(cube.APIKey, prev.APIKey)
+ out.Cube = &cube
+ }
+ if out.E2B != nil {
+ e2b := *out.E2B
+ var prev E2BSandboxConfig
+ if existing != nil && existing.E2B != nil {
+ prev = *existing.E2B
+ }
+ e2b.APIKey = PreserveIfRedacted(e2b.APIKey, prev.APIKey)
+ out.E2B = &e2b
+ }
+ // Only keys present in incoming survive: deleting a row in the UI must
+ // actually remove the variable rather than silently restore it.
+ if len(out.EnvVars) > 0 {
+ envVars := make(map[string]string, len(out.EnvVars))
+ for name, value := range out.EnvVars {
+ prev := ""
+ if existing != nil {
+ prev = existing.EnvVars[name]
+ }
+ envVars[name] = PreserveIfRedacted(value, prev)
+ }
+ out.EnvVars = envVars
+ }
+
+ return &out
+}
diff --git a/internal/types/config_redaction_sandbox_test.go b/internal/types/config_redaction_sandbox_test.go
new file mode 100644
index 000000000..f7022da8f
--- /dev/null
+++ b/internal/types/config_redaction_sandbox_test.go
@@ -0,0 +1,95 @@
+package types
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestSandboxConfigForResponseMasksSecrets(t *testing.T) {
+ cfg := &TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &E2BSandboxConfig{APIKey: "e2b-secret", APIURL: "https://api.e2b.dev"},
+ Cube: &CubeSandboxConfig{APIKey: "cube-secret", APIURL: "http://cube"},
+ EnvVars: map[string]string{"HF_TOKEN": "hf-secret"},
+ }
+
+ out := SandboxConfigForResponse(cfg, true)
+
+ require.Equal(t, RedactedSecretPlaceholder, out.E2B.APIKey)
+ require.Equal(t, RedactedSecretPlaceholder, out.Cube.APIKey)
+ require.Equal(t, RedactedSecretPlaceholder, out.EnvVars["HF_TOKEN"])
+ // Non-secret fields stay visible.
+ require.Equal(t, "https://api.e2b.dev", out.E2B.APIURL)
+ require.Equal(t, "e2b", out.SandboxType)
+ // Original must be untouched.
+ require.Equal(t, "e2b-secret", cfg.E2B.APIKey)
+ require.Equal(t, "hf-secret", cfg.EnvVars["HF_TOKEN"])
+}
+
+func TestSandboxConfigForResponseSkipsMaskingWhenDisabled(t *testing.T) {
+ cfg := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: "e2b-secret"}}
+
+ out := SandboxConfigForResponse(cfg, false)
+
+ require.Equal(t, "e2b-secret", out.E2B.APIKey)
+}
+
+func TestSandboxConfigForResponseEmptySecretStaysEmpty(t *testing.T) {
+ cfg := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: ""}}
+
+ out := SandboxConfigForResponse(cfg, true)
+
+ require.Empty(t, out.E2B.APIKey, "an unset secret must not become a placeholder")
+}
+
+func TestSandboxConfigForResponseNil(t *testing.T) {
+ require.Nil(t, SandboxConfigForResponse(nil, true))
+}
+
+func TestMergeSandboxConfigForUpdatePreservesRedactedSecrets(t *testing.T) {
+ existing := &TenantSandboxConfig{
+ E2B: &E2BSandboxConfig{APIKey: "old-e2b"},
+ Cube: &CubeSandboxConfig{APIKey: "old-cube"},
+ EnvVars: map[string]string{"HF_TOKEN": "old-hf", "GONE": "old-gone"},
+ }
+ incoming := &TenantSandboxConfig{
+ E2B: &E2BSandboxConfig{APIKey: RedactedSecretPlaceholder}, // untouched by user
+ Cube: &CubeSandboxConfig{APIKey: "new-cube"}, // user typed a new key
+ EnvVars: map[string]string{"HF_TOKEN": RedactedSecretPlaceholder},
+ }
+
+ out := MergeSandboxConfigForUpdate(incoming, existing)
+
+ require.Equal(t, "old-e2b", out.E2B.APIKey, "placeholder must resolve to the stored secret")
+ require.Equal(t, "new-cube", out.Cube.APIKey, "an explicitly typed secret must win")
+ require.Equal(t, "old-hf", out.EnvVars["HF_TOKEN"])
+ require.NotContains(t, out.EnvVars, "GONE", "env vars removed by the user must not resurrect")
+}
+
+func TestMergeSandboxConfigForUpdateHandlesNilExisting(t *testing.T) {
+ incoming := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: RedactedSecretPlaceholder}}
+
+ out := MergeSandboxConfigForUpdate(incoming, nil)
+
+ require.Empty(t, out.E2B.APIKey, "placeholder with no stored value resolves to empty")
+}
+
+func TestMergeSandboxConfigForUpdateNilIncoming(t *testing.T) {
+ require.Nil(t, MergeSandboxConfigForUpdate(nil, &TenantSandboxConfig{}))
+}
+
+func TestMergeSandboxConfigForUpdateDoesNotMutateInputs(t *testing.T) {
+ existing := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: "old-e2b"}}
+ incoming := &TenantSandboxConfig{
+ E2B: &E2BSandboxConfig{APIKey: RedactedSecretPlaceholder},
+ EnvVars: map[string]string{"HF_TOKEN": RedactedSecretPlaceholder},
+ }
+
+ _ = MergeSandboxConfigForUpdate(incoming, existing)
+
+ require.Equal(t, RedactedSecretPlaceholder, incoming.E2B.APIKey,
+ "merge must not mutate the incoming payload")
+ require.Equal(t, "old-e2b", existing.E2B.APIKey,
+ "merge must not mutate the stored config")
+}
diff --git a/internal/types/const.go b/internal/types/const.go
index 43f8e44e6..4ad4677ca 100644
--- a/internal/types/const.go
+++ b/internal/types/const.go
@@ -27,6 +27,23 @@ const (
// SessionTenantIDContextKey is the context key for session owner's tenant ID.
// When set (e.g. in pipeline with shared agent), session/message lookups use this instead of TenantIDContextKey.
SessionTenantIDContextKey ContextKey = "SessionTenantID"
+ // SessionIDContextKey carries the current session ID through the chat pipeline
+ // so that stateful sandbox backends (notably CubeSandbox) can route script
+ // execution to the persistent, per-session MicroVM instance.
+ SessionIDContextKey ContextKey = "SessionID"
+ // SandboxTenantIDContextKey carries the tenant that owns the session whose
+ // sandbox is being addressed, which is NOT always the tenant in
+ // TenantIDContextKey: a shared agent runs under the agent owner's tenant so
+ // that models/KBs/named sandbox configs resolve in the sharing workspace.
+ //
+ // The session→sandbox binding must stay keyed by the session owner instead,
+ // because session deletion tears the sandbox down from a plain HTTP request
+ // that only ever knows the session's own tenant. Keying the binding on the
+ // borrowed tenant would leave that teardown looking up a key nobody wrote,
+ // abandoning a paused MicroVM that keeps billing. It is deliberately a
+ // distinct key from SessionTenantIDContextKey, which also re-scopes
+ // session/message repository lookups. See SandboxTenantIDFromContext.
+ SandboxTenantIDContextKey ContextKey = "SandboxTenantID"
// EmbedQueryContextKey is the context key for embedding query text
EmbedQueryContextKey ContextKey = "EmbedQuery"
// WikiEditSourceContextKey carries who is authoring the current wiki
diff --git a/internal/types/context_helpers.go b/internal/types/context_helpers.go
index 9a641fdca..01aaeac7f 100644
--- a/internal/types/context_helpers.go
+++ b/internal/types/context_helpers.go
@@ -160,6 +160,51 @@ func SessionTenantIDFromContext(ctx context.Context) (uint64, bool) {
return TenantIDFromContext(ctx)
}
+// WithSessionID returns a derived context carrying the current session ID.
+// Stateful sandbox backends (e.g. CubeSandbox) rely on this key to route
+// script execution to the per-session persistent MicroVM instance.
+func WithSessionID(ctx context.Context, sessionID string) context.Context {
+ if sessionID == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, SessionIDContextKey, sessionID)
+}
+
+// SessionIDFromContext extracts the current session ID from ctx.
+// Returns ("", false) when the key is absent or the value is not a non-empty string.
+func SessionIDFromContext(ctx context.Context) (string, bool) {
+ if ctx == nil {
+ return "", false
+ }
+ v, ok := ctx.Value(SessionIDContextKey).(string)
+ return v, ok && v != ""
+}
+
+// WithSandboxTenantID records the session-owner tenant that session→sandbox
+// bindings must be keyed by, independently of the tenant the rest of the
+// pipeline runs as. Callers set it wherever they swap TenantIDContextKey for a
+// shared agent's workspace.
+func WithSandboxTenantID(ctx context.Context, tenantID uint64) context.Context {
+ if tenantID == 0 {
+ return ctx
+ }
+ return context.WithValue(ctx, SandboxTenantIDContextKey, tenantID)
+}
+
+// SandboxTenantIDFromContext returns the tenant to key session→sandbox
+// bindings by. It falls back to TenantIDFromContext, which is correct for every
+// path that never borrows another workspace's tenant: there the request tenant
+// already IS the session owner.
+func SandboxTenantIDFromContext(ctx context.Context) (uint64, bool) {
+ if ctx == nil {
+ return 0, false
+ }
+ if v, ok := ctx.Value(SandboxTenantIDContextKey).(uint64); ok && v != 0 {
+ return v, true
+ }
+ return TenantIDFromContext(ctx)
+}
+
// WithMCPOAuthNonInteractive marks ctx as originating from a channel that cannot
// complete an in-conversation MCP OAuth prompt (e.g. an IM bot). The agent uses
// this to emit a one-shot authorization notice instead of blocking on the OAuth
diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go
index bbba158a4..6160c50dc 100644
--- a/internal/types/custom_agent.go
+++ b/internal/types/custom_agent.go
@@ -149,6 +149,17 @@ type CustomAgentConfig struct {
SkillsSelectionMode string `yaml:"skills_selection_mode" json:"skills_selection_mode"`
// Selected skill names (only used when SkillsSelectionMode is "selected")
SelectedSkills []string `yaml:"selected_skills" json:"selected_skills"`
+
+ // ===== Sandbox Settings =====
+ // SandboxConfigID selects which workspace sandbox config this agent's
+ // skill scripts run on. Empty means the deployment-wide
+ // WEKNORA_SANDBOX_* defaults.
+ //
+ // This references the LOGICAL config, never a specific revision: keeping
+ // the indirection here is what would let credential rotation happen
+ // without re-pointing every agent (see the spec's §4.8).
+ SandboxConfigID string `yaml:"sandbox_config_id" json:"sandbox_config_id,omitempty"`
+
// ===== Knowledge Base Settings =====
// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`
diff --git a/internal/types/interfaces/custom_agent.go b/internal/types/interfaces/custom_agent.go
index f45b5d803..28a4b2c17 100644
--- a/internal/types/interfaces/custom_agent.go
+++ b/internal/types/interfaces/custom_agent.go
@@ -136,4 +136,18 @@ type CustomAgentRepository interface {
// CountByModelID counts active agents in the tenant whose config references
// the given model ID (chat, rerank, VLM, ASR, query-understand, etc.).
CountByModelID(ctx context.Context, tenantID uint64, modelID string) (int64, error)
+
+ // CountBySandboxConfigID counts agents pointing at a sandbox config.
+ //
+ // Used only to warn the admin which agents reference a config; never use it
+ // to refuse operations. Agent references are permanent state, so blocking on
+ // them would make credential rotation impossible.
+ CountBySandboxConfigID(ctx context.Context, tenantID uint64, configID string) (int64, error)
+
+ // ListNamesBySandboxConfigID returns agent names pointing at a sandbox config.
+ //
+ // Used only to warn the admin which agents reference a config; never use it
+ // to refuse operations. Agent references are permanent state, so blocking on
+ // them would make credential rotation impossible.
+ ListNamesBySandboxConfigID(ctx context.Context, tenantID uint64, configID string) ([]string, error)
}
diff --git a/internal/types/interfaces/message.go b/internal/types/interfaces/message.go
index 310d3c018..25c663a30 100644
--- a/internal/types/interfaces/message.go
+++ b/internal/types/interfaces/message.go
@@ -57,6 +57,12 @@ type MessageService interface {
// GetChatHistoryKBStats returns statistics about the chat history knowledge base (indexed message count, etc.)
GetChatHistoryKBStats(ctx context.Context) (*types.ChatHistoryKBStats, error)
+
+ // GetSessionArtifacts returns every skill-produced MessageArtifact
+ // recorded against any assistant message of the session. Used to power
+ // the frontend "download files generated in this session" drawer and
+ // to clean up storage blobs on session deletion.
+ GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error)
}
// MessageRepository defines the message repository interface
@@ -95,4 +101,13 @@ type MessageRepository interface {
GetKnowledgeIDsBySessionID(ctx context.Context, sessionID string) ([]string, error)
// UpdateMessageKnowledgeID updates the knowledge_id field for a message
UpdateMessageKnowledgeID(ctx context.Context, messageID string, knowledgeID string) error
+ // GetSessionArtifacts returns every skill-produced MessageArtifact recorded
+ // against any assistant message of the session, in creation order. The
+ // implementation only projects the artifacts JSONB column, so it stays
+ // cheap even for long conversations. Empty slice + nil error means the
+ // session has no artifacts yet (never an error).
+ GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error)
+ // GetSessionAttachments returns every user-uploaded attachment recorded in
+ // the session. Implementations should project only the attachments column.
+ GetSessionAttachments(ctx context.Context, sessionID string) (types.MessageAttachments, error)
}
diff --git a/internal/types/message.go b/internal/types/message.go
index c352b267e..99d2be7cf 100644
--- a/internal/types/message.go
+++ b/internal/types/message.go
@@ -168,6 +168,56 @@ func (m *MessageAttachments) Scan(value interface{}) error {
return json.Unmarshal(b, m)
}
+// MessageArtifact represents a file produced by a skill script during a chat
+// turn. Unlike MessageAttachment (which stores files uploaded by the user),
+// MessageArtifact records files that the sandbox generated on the model's
+// behalf and that WeKnora has persisted to its file service so the user can
+// download them after the sandbox is reaped.
+//
+// URL is the provider-scoped storage path (e.g. "local://tenant/..."), never
+// exposed directly to the client. SourcePath + ModTime form the sandbox-side
+// identity used by ArtifactCollector to de-duplicate files across multi-turn
+// runs (see docs/superpowers/specs/2026-07-10-skill-artifact-download-design.md).
+type MessageArtifact struct {
+ URL string `json:"url"` // Storage URL (provider://path); persisted, not sent to client
+ FileName string `json:"file_name"` // Original filename inside the sandbox
+ FileType string `json:"file_type"` // File extension (e.g., ".pptx", ".pdf")
+ FileSize int64 `json:"file_size"` // File size in bytes
+ SourcePath string `json:"source_path"` // Absolute path inside the sandbox (used for diff)
+ ModTime time.Time `json:"mod_time"` // Sandbox-side modification time (used for diff)
+ CreatedAt time.Time `json:"created_at"` // When WeKnora persisted the blob
+}
+
+// MessageArtifacts is a slice of MessageArtifact for database storage.
+type MessageArtifacts []MessageArtifact
+
+// Value implements the driver.Valuer interface for database serialization
+func (m MessageArtifacts) Value() (driver.Value, error) {
+ if m == nil {
+ return json.Marshal([]MessageArtifact{})
+ }
+ return json.Marshal(m)
+}
+
+// Scan implements the sql.Scanner interface for database deserialization
+func (m *MessageArtifacts) Scan(value interface{}) error {
+ if value == nil {
+ *m = make(MessageArtifacts, 0)
+ return nil
+ }
+ var b []byte
+ switch v := value.(type) {
+ case []byte:
+ b = v
+ case string:
+ b = []byte(v)
+ default:
+ *m = make(MessageArtifacts, 0)
+ return nil
+ }
+ return json.Unmarshal(b, m)
+}
+
// MentionedItems is a slice of MentionedItem for database storage
type MentionedItems []MentionedItem
@@ -225,6 +275,10 @@ type Message struct {
Images MessageImages `json:"images,omitempty" gorm:"type:jsonb;column:images"`
// Attached files (documents, audio, etc., for user messages)
Attachments MessageAttachments `json:"attachments,omitempty" gorm:"type:jsonb;column:attachments"`
+ // Skill-generated files produced during this assistant turn (assistant messages only).
+ // Populated by ArtifactCollector after the sandbox finishes, referenced by the
+ // artifact download endpoint. Empty for user messages and turns without skills.
+ Artifacts MessageArtifacts `json:"artifacts,omitempty" gorm:"type:jsonb;column:artifacts"`
// Whether message generation is complete
IsCompleted bool `json:"is_completed"`
// Whether this response is a fallback (no knowledge base match found)
@@ -353,6 +407,9 @@ func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {
if m.Attachments == nil {
m.Attachments = make(MessageAttachments, 0)
}
+ if m.Artifacts == nil {
+ m.Artifacts = make(MessageArtifacts, 0)
+ }
return nil
}
diff --git a/internal/types/message_test.go b/internal/types/message_test.go
new file mode 100644
index 000000000..9f8abf429
--- /dev/null
+++ b/internal/types/message_test.go
@@ -0,0 +1,138 @@
+package types
+
+import (
+ "bytes"
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+// TestMessageArtifacts_ValueScanRoundTrip pins the JSONB serialisation
+// contract used by GORM: (Value → bytes → Scan) must produce an equivalent
+// slice, including a zero-time modified-at (which must survive JSON's
+// RFC3339 encoding).
+func TestMessageArtifacts_ValueScanRoundTrip(t *testing.T) {
+ mod := time.Date(2026, 7, 10, 10, 20, 30, 0, time.UTC)
+ created := time.Date(2026, 7, 10, 10, 20, 31, 0, time.UTC)
+
+ original := MessageArtifacts{
+ {
+ URL: "local://42/report.pptx",
+ FileName: "report.pptx",
+ FileType: ".pptx",
+ FileSize: 285432,
+ SourcePath: "/workspace/output/report.pptx",
+ ModTime: mod,
+ CreatedAt: created,
+ },
+ {
+ // Second entry to cover slice-of-many + empty ModTime edge.
+ URL: "local://42/notes.txt",
+ FileName: "notes.txt",
+ FileType: ".txt",
+ FileSize: 17,
+ SourcePath: "/workspace/output/notes.txt",
+ CreatedAt: created,
+ },
+ }
+
+ raw, err := original.Value()
+ if err != nil {
+ t.Fatalf("Value() error = %v", err)
+ }
+ rawBytes, ok := raw.([]byte)
+ if !ok {
+ t.Fatalf("Value() returned %T, want []byte", raw)
+ }
+ // Extra sanity: the bytes must be valid JSON, and re-serialising the
+ // decoded value should be byte-equal.
+ var probe []map[string]any
+ if err := json.Unmarshal(rawBytes, &probe); err != nil {
+ t.Fatalf("Value() emitted invalid JSON: %v (bytes=%q)", err, rawBytes)
+ }
+ if len(probe) != 2 {
+ t.Fatalf("expected 2 encoded artifacts, got %d", len(probe))
+ }
+
+ var decoded MessageArtifacts
+ if err := decoded.Scan(rawBytes); err != nil {
+ t.Fatalf("Scan([]byte) error = %v", err)
+ }
+ if len(decoded) != len(original) {
+ t.Fatalf("Scan length = %d, want %d", len(decoded), len(original))
+ }
+ for i := range original {
+ if decoded[i].URL != original[i].URL ||
+ decoded[i].FileName != original[i].FileName ||
+ decoded[i].FileType != original[i].FileType ||
+ decoded[i].FileSize != original[i].FileSize ||
+ decoded[i].SourcePath != original[i].SourcePath {
+ t.Fatalf("artifact %d mismatch: got=%+v want=%+v", i, decoded[i], original[i])
+ }
+ if !decoded[i].ModTime.Equal(original[i].ModTime) {
+ t.Fatalf("artifact %d mod_time mismatch: got=%s want=%s",
+ i, decoded[i].ModTime, original[i].ModTime)
+ }
+ if !decoded[i].CreatedAt.Equal(original[i].CreatedAt) {
+ t.Fatalf("artifact %d created_at mismatch: got=%s want=%s",
+ i, decoded[i].CreatedAt, original[i].CreatedAt)
+ }
+ }
+
+ // Also assert Scan(string) is accepted — some drivers (e.g. sqlite) return
+ // TEXT for JSONB columns, so the code path must not care.
+ var fromString MessageArtifacts
+ if err := fromString.Scan(string(rawBytes)); err != nil {
+ t.Fatalf("Scan(string) error = %v", err)
+ }
+ if len(fromString) != len(original) {
+ t.Fatalf("Scan(string) length = %d, want %d", len(fromString), len(original))
+ }
+}
+
+// TestMessageArtifacts_ScanNil ensures a NULL column materialises as an
+// empty (but non-nil) slice, matching the invariant Message.BeforeCreate
+// establishes.
+func TestMessageArtifacts_ScanNil(t *testing.T) {
+ var m MessageArtifacts
+ if err := m.Scan(nil); err != nil {
+ t.Fatalf("Scan(nil) error = %v", err)
+ }
+ if m == nil {
+ t.Fatal("Scan(nil) yielded nil slice, want empty non-nil")
+ }
+ if len(m) != 0 {
+ t.Fatalf("Scan(nil) length = %d, want 0", len(m))
+ }
+}
+
+// TestMessageArtifacts_ScanUnknownType covers the fallback branch: a driver
+// returning an unexpected type (e.g. int) must produce an empty slice and
+// no error, matching the defensive contract shared with MessageImages/
+// MessageAttachments.
+func TestMessageArtifacts_ScanUnknownType(t *testing.T) {
+ var m MessageArtifacts
+ if err := m.Scan(12345); err != nil {
+ t.Fatalf("Scan(int) unexpected error = %v", err)
+ }
+ if len(m) != 0 {
+ t.Fatalf("Scan(unknown) length = %d, want 0", len(m))
+ }
+}
+
+// TestMessageArtifacts_ValueNil pins the "nil slice → JSON empty array" path
+// so a fresh Message without artifacts serialises as `[]` rather than `null`.
+func TestMessageArtifacts_ValueNil(t *testing.T) {
+ var m MessageArtifacts
+ v, err := m.Value()
+ if err != nil {
+ t.Fatalf("Value() error = %v", err)
+ }
+ b, ok := v.([]byte)
+ if !ok {
+ t.Fatalf("Value() returned %T, want []byte", v)
+ }
+ if !bytes.Equal(b, []byte("[]")) {
+ t.Fatalf("Value(nil slice) = %q, want []", b)
+ }
+}
diff --git a/internal/types/sandbox_tenant_context_test.go b/internal/types/sandbox_tenant_context_test.go
new file mode 100644
index 000000000..0e78fb62a
--- /dev/null
+++ b/internal/types/sandbox_tenant_context_test.go
@@ -0,0 +1,52 @@
+package types
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// Every path that does not borrow another workspace's tenant must keep working
+// without setting the key at all: there the request tenant already is the
+// session owner. Session deletion relies on exactly this fallback.
+func TestSandboxTenantIDFallsBackToRequestTenant(t *testing.T) {
+ ctx := context.WithValue(context.Background(), TenantIDContextKey, uint64(7))
+
+ got, ok := SandboxTenantIDFromContext(ctx)
+ require.True(t, ok)
+ require.Equal(t, uint64(7), got)
+}
+
+// A shared agent runs under the agent owner's tenant so models, KBs and named
+// sandbox configs resolve in the sharing workspace. The sandbox binding must
+// stay on the session owner regardless, because DeleteSession tears it down
+// from a request that only ever knows the session's own tenant.
+func TestSandboxTenantIDOverridesBorrowedTenant(t *testing.T) {
+ const sessionOwner, agentOwner = uint64(7), uint64(99)
+
+ ctx := context.WithValue(context.Background(), TenantIDContextKey, agentOwner)
+ ctx = WithSandboxTenantID(ctx, sessionOwner)
+
+ got, ok := SandboxTenantIDFromContext(ctx)
+ require.True(t, ok)
+ require.Equal(t, sessionOwner, got,
+ "binding tenant must be the session owner, not the borrowed agent tenant")
+
+ // The borrowed tenant must survive untouched: it is what makes the shared
+ // agent's own config resolve.
+ borrowed, ok := TenantIDFromContext(ctx)
+ require.True(t, ok)
+ require.Equal(t, agentOwner, borrowed)
+}
+
+// A zero tenant would silently poison the binding key, so it is ignored rather
+// than recorded.
+func TestWithSandboxTenantIDIgnoresZero(t *testing.T) {
+ ctx := context.WithValue(context.Background(), TenantIDContextKey, uint64(7))
+ ctx = WithSandboxTenantID(ctx, 0)
+
+ got, ok := SandboxTenantIDFromContext(ctx)
+ require.True(t, ok)
+ require.Equal(t, uint64(7), got)
+}
diff --git a/internal/types/session.go b/internal/types/session.go
index e6f3b7a74..0a490380b 100644
--- a/internal/types/session.go
+++ b/internal/types/session.go
@@ -98,6 +98,15 @@ type Session struct {
// avoid a new migration; the shape used today is `SessionLastRequestState`.
LastRequestState *SessionLastRequestState `json:"last_request_state,omitempty" gorm:"column:agent_config;type:jsonb"`
+ // SandboxConfigID pins which sandbox config this session's CURRENT live
+ // sandbox was created on. Empty means no live sandbox;
+ // SandboxConfigIDGlobalDefault means the deployment-wide default config.
+ //
+ // This is an ephemeral pin that dies with the sandbox, not a permanent
+ // owner: sessions outlive sandboxes by months, so treating it as
+ // permanent would make "no session references this config" never true.
+ SandboxConfigID string `json:"sandbox_config_id,omitempty" gorm:"type:varchar(36)"`
+
// // Strategy configuration
// KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
// MaxRounds int `json:"max_rounds"` // 多轮保持轮数
diff --git a/internal/types/tenant.go b/internal/types/tenant.go
index ce24d61dc..0a2538bfc 100644
--- a/internal/types/tenant.go
+++ b/internal/types/tenant.go
@@ -617,3 +617,198 @@ func (c *StorageEngineConfig) Scan(value interface{}) error {
}
return json.Unmarshal(b, c)
}
+
+// TenantSandboxConfig is one named sandbox backend a workspace maintains.
+//
+// It is self-contained: provider fields are NOT inherited from the deployment's
+// WEKNORA_SANDBOX_* values, which only back agents that selected no config at
+// all. Leaving a required provider field empty is rejected on save rather than
+// filled in from the environment — see sandbox.MissingRequiredFields for the
+// list and internal/sandbox/tenant_config.go for why inheritance was dropped.
+type TenantSandboxConfig struct {
+ // SandboxType selects the sandbox backend. Named configs must set it to
+ // "cube" or "e2b"; "docker", "local" and "disabled" appear only on the
+ // workspace policy row.
+ SandboxType string `json:"sandbox_type,omitempty"`
+
+ // ── 通用配置(跨后端生效)──────────────────────────────────
+
+ // DefaultTimeoutSec is the per-execution timeout in seconds. 0 keeps the
+ // deployment's WEKNORA_SANDBOX_TIMEOUT: an execution guardrail is operator
+ // policy rather than part of this backend's identity, so it is the one
+ // value a named config still takes from the environment.
+ DefaultTimeoutSec int `json:"default_timeout_sec,omitempty"`
+
+ // EnvVars are additional environment variables injected into every
+ // sandbox created for this tenant. 🔒 Values are encrypted at rest.
+ // These become visible to all scripts running in the tenant's
+ // sandboxes — do not place secrets here that scripts must not access.
+ EnvVars map[string]string `json:"env_vars,omitempty"`
+
+ // VolumeMount configures an optional shared volume mounted into every
+ // sandbox created for this tenant. Currently used for tenant-installed
+ // skills, but the configuration itself is skill-agnostic and can serve
+ // any volume-mount use case (shared datasets, pre-installed toolchains,
+ // etc.).
+ VolumeMount *VolumeMountConfig `json:"volume_mount,omitempty"`
+
+ // ── 后端专属配置(同一时刻只有一个生效,由 SandboxType 决定)───
+
+ Cube *CubeSandboxConfig `json:"cube,omitempty"`
+ E2B *E2BSandboxConfig `json:"e2b,omitempty"`
+ Docker *DockerSandboxConfig `json:"docker,omitempty"`
+}
+
+// CubeSandboxConfig addresses one CubeSandbox deployment. APIURL, ProxyURL,
+// SandboxDomain and TemplateID are all required; APIKey is optional because the
+// common single-node setup runs unauthenticated.
+type CubeSandboxConfig struct {
+ APIURL string `json:"api_url,omitempty"`
+ ProxyURL string `json:"proxy_url,omitempty"`
+ SandboxDomain string `json:"sandbox_domain,omitempty"`
+ APIKey string `json:"api_key,omitempty"` // 加密
+ TemplateID string `json:"template_id,omitempty"`
+
+ // HTTPTimeoutSec bounds each HTTP call to the sandbox control plane.
+ // 0 means use the built-in default (30s), never the deployment's value.
+ HTTPTimeoutSec int `json:"http_timeout_sec,omitempty"`
+
+ CubeSandboxTTLSeconds int `json:"cube_sandbox_ttl_seconds,omitempty"`
+}
+
+// E2BSandboxConfig addresses one E2B account. APIKey and TemplateID are
+// required; APIURL and SandboxDomain are optional because go-e2b resolves both
+// on its own when they are empty.
+type E2BSandboxConfig struct {
+ APIURL string `json:"api_url,omitempty"`
+ SandboxDomain string `json:"sandbox_domain,omitempty"`
+ APIKey string `json:"api_key,omitempty"` // 加密
+ TemplateID string `json:"template_id,omitempty"`
+
+ // HTTPTimeoutSec bounds each HTTP call to the sandbox control plane.
+ // 0 means use the built-in default (30s), never the deployment's value.
+ HTTPTimeoutSec int `json:"http_timeout_sec,omitempty"`
+
+ E2BSandboxTTLSeconds int `json:"e2b_sandbox_ttl_seconds,omitempty"`
+}
+
+type DockerSandboxConfig struct {
+ Image string `json:"image,omitempty"`
+}
+
+// VolumeMountConfig configures a shared volume mount into every sandbox
+// created for this tenant. Currently implemented for E2B volumes (used to
+// share tenant-installed skills across sandbox sessions), but the schema is
+// intentionally skill-agnostic so it can serve other volume-based use cases
+// in the future.
+type VolumeMountConfig struct {
+ // Enabled toggles the volume mount for this tenant.
+ Enabled bool `json:"enabled"`
+
+ // MountPath is the sandbox-internal path where the volume is mounted.
+ // Default: /weknora/tenant/skills (customizable per use case).
+ MountPath string `json:"mount_path,omitempty"`
+
+ // Provider identifies the volume backend. Currently "e2b" or "cube".
+ Provider string `json:"provider,omitempty"`
+
+ // VolumeID is the provider-specific volume identifier, populated after
+ // EnsureVolume / CreateVolume succeeds.
+ VolumeID string `json:"volume_id,omitempty"`
+
+ // VolumeName is the human-readable volume name, e.g.
+ // "weknora-tenant-<id>-skills".
+ VolumeName string `json:"volume_name,omitempty"`
+
+ // VolumeOwnerFingerprint = sha256(provider + APIKey + APIURL).
+ // Used to detect when the tenant switched to a different backend or
+ // API key, at which point the volume is no longer reachable and must
+ // be recreated.
+ VolumeOwnerFingerprint string `json:"volume_owner_fingerprint,omitempty"`
+}
+
+// Value implements the driver.Valuer interface. Every secret-bearing field
+// (Cube.APIKey, E2B.APIKey and all EnvVars values) is encrypted before
+// persisting. EnvVars are included because environment variables routinely
+// carry credentials, and their values are handed to tenant scripts verbatim.
+// The receiver is never mutated: nested structs and the map are copied first.
+func (c *TenantSandboxConfig) Value() (driver.Value, error) {
+ if c == nil {
+ return nil, nil
+ }
+ cp := *c
+ key := utils.GetAESKey()
+
+ encrypt := func(plain string) string {
+ if plain == "" || key == nil {
+ return plain
+ }
+ encrypted, err := utils.EncryptAESGCM(plain, key)
+ if err != nil {
+ return plain
+ }
+ return encrypted
+ }
+
+ if c.Cube != nil {
+ cube := *c.Cube
+ cube.APIKey = encrypt(cube.APIKey)
+ cp.Cube = &cube
+ }
+ if c.E2B != nil {
+ e2b := *c.E2B
+ e2b.APIKey = encrypt(e2b.APIKey)
+ cp.E2B = &e2b
+ }
+ // Keys stay readable so operators can still see which variables are set.
+ if len(c.EnvVars) > 0 {
+ envVars := make(map[string]string, len(c.EnvVars))
+ for name, value := range c.EnvVars {
+ envVars[name] = encrypt(value)
+ }
+ cp.EnvVars = envVars
+ }
+
+ return json.Marshal(&cp)
+}
+
+// Scan implements the sql.Scanner interface. Secrets that cannot be decrypted
+// (missing or rotated SYSTEM_AES_KEY) are blanked and logged rather than
+// failing the whole load, matching ModelParameters.Scan — a tenant must stay
+// listable even if its sandbox credentials became unreadable.
+func (c *TenantSandboxConfig) Scan(value interface{}) error {
+ if value == nil {
+ return nil
+ }
+ b, ok := value.([]byte)
+ if !ok {
+ return nil
+ }
+ if err := json.Unmarshal(b, c); err != nil {
+ return err
+ }
+
+ decrypt := func(stored, label string) string {
+ if stored == "" {
+ return ""
+ }
+ if plain, ok := utils.DecryptStoredSecretLenient(stored); ok {
+ return plain
+ }
+ log.Printf("[crypto] tenant_sandbox_config.%s: decrypt failed "+
+ "(SYSTEM_AES_KEY missing/rotated?), treating as unconfigured", label)
+ return ""
+ }
+
+ if c.Cube != nil {
+ c.Cube.APIKey = decrypt(c.Cube.APIKey, "cube.api_key")
+ }
+ if c.E2B != nil {
+ c.E2B.APIKey = decrypt(c.E2B.APIKey, "e2b.api_key")
+ }
+ for name, stored := range c.EnvVars {
+ c.EnvVars[name] = decrypt(stored, "env_vars."+name)
+ }
+
+ return nil
+}
diff --git a/internal/types/tenant_sandbox_config_entity.go b/internal/types/tenant_sandbox_config_entity.go
new file mode 100644
index 000000000..1f4859a36
--- /dev/null
+++ b/internal/types/tenant_sandbox_config_entity.go
@@ -0,0 +1,71 @@
+// Package types: sandbox backend config entity.
+//
+// A workspace holds several named sandbox configs so different agents can run
+// on different backends (e.g. a big-memory E2B account for data analysis, a
+// self-hosted Cube for everything else). The credential-bearing payload lives
+// in Config, reusing TenantSandboxConfig's encrypted Value/Scan hooks.
+package types
+
+import (
+ "time"
+
+ "gorm.io/gorm"
+)
+
+// SandboxConfigIDGlobalDefault marks a sandbox created on the deployment-wide
+// WEKNORA_SANDBOX_* configuration rather than on a stored config row.
+//
+// A sentinel rather than the empty string, so NULL on sessions.sandbox_config_id
+// unambiguously means "this session has no live sandbox".
+const SandboxConfigIDGlobalDefault = "-"
+
+// SandboxCordonLease bounds how long a cordon is honoured. Identity changes
+// take the cordon for the duration of two provider API calls; anything older
+// is a crashed handler's leftover and must not wedge the config.
+const SandboxCordonLease = 2 * time.Minute
+
+// SandboxWorkspacePolicyConfigName is the reserved row name for the workspace-
+// level "disable script execution for deployment-default agents" toggle. It is
+// hidden from the management list and updated via the workspace-policy API.
+const SandboxWorkspacePolicyConfigName = "__workspace_scripts_policy__"
+
+// IsSandboxWorkspacePolicyRow reports whether e is the internal policy row.
+func IsSandboxWorkspacePolicyRow(e *TenantSandboxConfigEntity) bool {
+ return e != nil && e.Name == SandboxWorkspacePolicyConfigName
+}
+
+// TenantSandboxConfigEntity is one named sandbox backend configuration.
+type TenantSandboxConfigEntity struct {
+ ID string `gorm:"type:varchar(36);primaryKey"`
+ TenantID uint64 `gorm:"index"`
+ Name string `gorm:"type:varchar(255);not null"`
+ Description string `gorm:"type:text"`
+
+ // SandboxType is promoted out of Config so listing and cleanup decisions
+ // do not have to decrypt and unmarshal the payload.
+ SandboxType string `gorm:"type:varchar(32);not null"`
+
+ Config *TenantSandboxConfig `gorm:"type:jsonb"`
+
+ // CordonedAt is held while identity fields are being changed. See
+ // IsCordoned: it is a lease, never a permanent lock.
+ CordonedAt *time.Time
+
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ DeletedAt gorm.DeletedAt `gorm:"index"`
+}
+
+// TableName pins the table so GORM's pluralizer cannot drift.
+func (e *TenantSandboxConfigEntity) TableName() string {
+ return "tenant_sandbox_configs"
+}
+
+// IsCordoned reports whether sandbox resolution must be refused for this
+// config right now.
+func (e *TenantSandboxConfigEntity) IsCordoned(now time.Time, lease time.Duration) bool {
+ if e == nil || e.CordonedAt == nil {
+ return false
+ }
+ return now.Sub(*e.CordonedAt) < lease
+}
diff --git a/internal/types/tenant_sandbox_config_entity_test.go b/internal/types/tenant_sandbox_config_entity_test.go
new file mode 100644
index 000000000..8608c4287
--- /dev/null
+++ b/internal/types/tenant_sandbox_config_entity_test.go
@@ -0,0 +1,50 @@
+package types
+
+import (
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestTenantSandboxConfigEntityTableName(t *testing.T) {
+ e := &TenantSandboxConfigEntity{}
+ require.Equal(t, "tenant_sandbox_configs", e.TableName())
+}
+
+// A cordon is a lease, not a permanent lock: a handler that crashes while
+// holding it must not wedge the config forever.
+func TestTenantSandboxConfigEntityIsCordoned(t *testing.T) {
+ now := time.Date(2026, 8, 4, 12, 0, 0, 0, time.UTC)
+ fresh := now.Add(-30 * time.Second)
+ stale := now.Add(-10 * time.Minute)
+
+ tests := []struct {
+ name string
+ at *time.Time
+ want bool
+ }{
+ {name: "never cordoned", at: nil, want: false},
+ {name: "fresh cordon blocks", at: &fresh, want: true},
+ {name: "stale cordon is ignored", at: &stale, want: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ e := &TenantSandboxConfigEntity{CordonedAt: tt.at}
+ require.Equal(t, tt.want, e.IsCordoned(now, SandboxCordonLease))
+ })
+ }
+}
+
+// A config row that was not found comes back as nil; treating that as cordoned
+// would refuse sandbox resolution for a config that does not exist.
+func TestNilEntityIsNotCordoned(t *testing.T) {
+ var e *TenantSandboxConfigEntity
+ require.False(t, e.IsCordoned(time.Now(), SandboxCordonLease))
+}
+
+// The value is persisted in sessions.sandbox_config_id and stamped onto sandbox
+// metadata, so changing it would orphan existing rows and sandboxes.
+func TestSandboxConfigIDGlobalDefaultValue(t *testing.T) {
+ require.Equal(t, "-", SandboxConfigIDGlobalDefault)
+}
diff --git a/internal/types/tenant_sandbox_config_test.go b/internal/types/tenant_sandbox_config_test.go
new file mode 100644
index 000000000..f46350a56
--- /dev/null
+++ b/internal/types/tenant_sandbox_config_test.go
@@ -0,0 +1,95 @@
+package types
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// setAESKey installs a valid 32-byte SYSTEM_AES_KEY for the test.
+func setAESKey(t *testing.T) {
+ t.Helper()
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+}
+
+func TestTenantSandboxConfigEncryptsSecretsAtRest(t *testing.T) {
+ setAESKey(t)
+
+ cfg := &TenantSandboxConfig{
+ SandboxType: "e2b",
+ E2B: &E2BSandboxConfig{APIKey: "e2b-secret", APIURL: "https://api.e2b.dev"},
+ Cube: &CubeSandboxConfig{APIKey: "cube-secret"},
+ EnvVars: map[string]string{"HF_TOKEN": "hf-secret", "PLAIN": "not-a-secret"},
+ }
+
+ raw, err := cfg.Value()
+ require.NoError(t, err)
+
+ serialized := string(raw.([]byte))
+ require.NotContains(t, serialized, "e2b-secret", "E2B API key must not be stored in plaintext")
+ require.NotContains(t, serialized, "cube-secret", "Cube API key must not be stored in plaintext")
+ require.NotContains(t, serialized, "hf-secret", "EnvVars values must not be stored in plaintext")
+ require.NotContains(t, serialized, "not-a-secret",
+ "EnvVars values must be encrypted regardless of content")
+ // Keys themselves stay readable so the config remains inspectable.
+ require.Contains(t, serialized, "HF_TOKEN")
+
+ var restored TenantSandboxConfig
+ require.NoError(t, restored.Scan(raw.([]byte)))
+
+ require.Equal(t, "e2b-secret", restored.E2B.APIKey)
+ require.Equal(t, "cube-secret", restored.Cube.APIKey)
+ require.Equal(t, "hf-secret", restored.EnvVars["HF_TOKEN"])
+ require.Equal(t, "not-a-secret", restored.EnvVars["PLAIN"])
+ require.Equal(t, "https://api.e2b.dev", restored.E2B.APIURL,
+ "non-secret fields stay untouched")
+}
+
+func TestTenantSandboxConfigValueDoesNotMutateReceiver(t *testing.T) {
+ setAESKey(t)
+
+ cfg := &TenantSandboxConfig{
+ E2B: &E2BSandboxConfig{APIKey: "e2b-secret"},
+ Cube: &CubeSandboxConfig{APIKey: "cube-secret"},
+ EnvVars: map[string]string{"HF_TOKEN": "hf-secret"},
+ }
+
+ _, err := cfg.Value()
+ require.NoError(t, err)
+
+ require.Equal(t, "e2b-secret", cfg.E2B.APIKey, "Value must not mutate the original struct")
+ require.Equal(t, "cube-secret", cfg.Cube.APIKey, "Value must not mutate the original struct")
+ require.Equal(t, "hf-secret", cfg.EnvVars["HF_TOKEN"], "Value must not mutate the original map")
+}
+
+func TestTenantSandboxConfigScanTolerantOfUndecryptableSecrets(t *testing.T) {
+ // A row written under a different/rotated key must not break loading the
+ // tenant; the secret is blanked and treated as unconfigured.
+ setAESKey(t)
+
+ payload, err := json.Marshal(map[string]any{
+ "sandbox_type": "e2b",
+ "e2b": map[string]string{"api_key": "enc:v1:not-really-valid-base64!!"},
+ "env_vars": map[string]string{"HF_TOKEN": "enc:v1:also-invalid!!"},
+ })
+ require.NoError(t, err)
+
+ var cfg TenantSandboxConfig
+ require.NoError(t, cfg.Scan(payload), "Scan must not fail on undecryptable secrets")
+ require.Empty(t, cfg.E2B.APIKey)
+ require.Empty(t, cfg.EnvVars["HF_TOKEN"])
+ require.Equal(t, "e2b", cfg.SandboxType, "non-secret fields still load")
+}
+
+func TestTenantSandboxConfigNilRoundTrip(t *testing.T) {
+ var cfg *TenantSandboxConfig
+
+ raw, err := cfg.Value()
+ require.NoError(t, err)
+ require.Nil(t, raw, "a nil config persists as SQL NULL")
+
+ var restored TenantSandboxConfig
+ require.NoError(t, restored.Scan(nil), "scanning NULL is a no-op")
+}
diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql
index d1baea4af..635cce402 100644
--- a/migrations/sqlite/000000_init.up.sql
+++ b/migrations/sqlite/000000_init.up.sql
@@ -148,6 +148,7 @@ CREATE TABLE IF NOT EXISTS sessions (
user_id VARCHAR(512),
is_pinned BOOLEAN NOT NULL DEFAULT 0,
pinned_at DATETIME,
+ sandbox_config_id VARCHAR(36),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
@@ -170,6 +171,7 @@ CREATE TABLE IF NOT EXISTS messages (
agent_steps TEXT DEFAULT NULL,
mentioned_items TEXT DEFAULT '[]',
images TEXT DEFAULT '[]',
+ artifacts TEXT DEFAULT '[]',
is_completed BOOLEAN NOT NULL DEFAULT 0,
is_fallback BOOLEAN NOT NULL DEFAULT 0,
channel VARCHAR(50) NOT NULL DEFAULT '',
@@ -557,6 +559,23 @@ CREATE INDEX IF NOT EXISTS idx_custom_agents_tenant_id ON custom_agents(tenant_i
CREATE INDEX IF NOT EXISTS idx_custom_agents_is_builtin ON custom_agents(is_builtin);
CREATE INDEX IF NOT EXISTS idx_custom_agents_deleted_at ON custom_agents(deleted_at);
+CREATE TABLE IF NOT EXISTS tenant_sandbox_configs (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ description TEXT,
+ sandbox_type VARCHAR(32) NOT NULL,
+ config TEXT NOT NULL DEFAULT '{}',
+ cordoned_at DATETIME,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ deleted_at DATETIME
+);
+CREATE INDEX IF NOT EXISTS idx_tenant_sandbox_configs_tenant_id ON tenant_sandbox_configs(tenant_id);
+CREATE INDEX IF NOT EXISTS idx_tenant_sandbox_configs_deleted_at ON tenant_sandbox_configs(deleted_at);
+CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_sandbox_configs_tenant_name
+ ON tenant_sandbox_configs(tenant_id, name) WHERE deleted_at IS NULL;
+
CREATE TABLE IF NOT EXISTS organizations (
id VARCHAR(36) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
diff --git a/migrations/versioned/000081_message_artifacts.down.sql b/migrations/versioned/000081_message_artifacts.down.sql
new file mode 100644
index 000000000..13b3fb1d3
--- /dev/null
+++ b/migrations/versioned/000081_message_artifacts.down.sql
@@ -0,0 +1 @@
+ALTER TABLE messages DROP COLUMN IF EXISTS artifacts;
diff --git a/migrations/versioned/000081_message_artifacts.up.sql b/migrations/versioned/000081_message_artifacts.up.sql
new file mode 100644
index 000000000..c1c828506
--- /dev/null
+++ b/migrations/versioned/000081_message_artifacts.up.sql
@@ -0,0 +1 @@
+ALTER TABLE messages ADD COLUMN IF NOT EXISTS artifacts JSONB DEFAULT '[]'::jsonb;
diff --git a/migrations/versioned/000082_tenant_sandbox_config.down.sql b/migrations/versioned/000082_tenant_sandbox_config.down.sql
new file mode 100644
index 000000000..fa6b53b32
--- /dev/null
+++ b/migrations/versioned/000082_tenant_sandbox_config.down.sql
@@ -0,0 +1,3 @@
+DO $$ BEGIN RAISE NOTICE '[Migration 000082 down] Dropping tenant_sandbox_configs'; END $$;
+
+DROP TABLE IF EXISTS tenant_sandbox_configs;
diff --git a/migrations/versioned/000082_tenant_sandbox_config.up.sql b/migrations/versioned/000082_tenant_sandbox_config.up.sql
new file mode 100644
index 000000000..32e51e18c
--- /dev/null
+++ b/migrations/versioned/000082_tenant_sandbox_config.up.sql
@@ -0,0 +1,25 @@
+-- Description: Store multiple named sandbox backend configs per workspace.
+-- Replaces the earlier single tenants.tenant_sandbox_config JSONB column: one
+-- workspace can now point different agents at different sandbox backends.
+DO $$ BEGIN RAISE NOTICE '[Migration 000082] Creating tenant_sandbox_configs'; END $$;
+
+CREATE TABLE IF NOT EXISTS tenant_sandbox_configs (
+ id VARCHAR(36) PRIMARY KEY,
+ tenant_id BIGINT NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ description TEXT,
+ sandbox_type VARCHAR(32) NOT NULL,
+ config JSONB NOT NULL,
+ cordoned_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ deleted_at TIMESTAMPTZ
+);
+
+COMMENT ON COLUMN tenant_sandbox_configs.config IS 'Sandbox backend config (endpoints, encrypted API keys, env vars, volume mount); shape matches types.TenantSandboxConfig';
+COMMENT ON COLUMN tenant_sandbox_configs.cordoned_at IS 'Short lease taken while identity fields (provider/URL/API key) are being changed; sandbox resolution is refused while it is fresh';
+
+CREATE INDEX IF NOT EXISTS idx_tenant_sandbox_configs_tenant
+ ON tenant_sandbox_configs (tenant_id) WHERE deleted_at IS NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_sandbox_configs_tenant_name
+ ON tenant_sandbox_configs (tenant_id, name) WHERE deleted_at IS NULL;
diff --git a/migrations/versioned/000083_session_sandbox_config.down.sql b/migrations/versioned/000083_session_sandbox_config.down.sql
new file mode 100644
index 000000000..986b8903f
--- /dev/null
+++ b/migrations/versioned/000083_session_sandbox_config.down.sql
@@ -0,0 +1,3 @@
+DO $$ BEGIN RAISE NOTICE '[Migration 000083 down] Dropping sessions.sandbox_config_id'; END $$;
+
+ALTER TABLE sessions DROP COLUMN IF EXISTS sandbox_config_id;
diff --git a/migrations/versioned/000083_session_sandbox_config.up.sql b/migrations/versioned/000083_session_sandbox_config.up.sql
new file mode 100644
index 000000000..05fbfa828
--- /dev/null
+++ b/migrations/versioned/000083_session_sandbox_config.up.sql
@@ -0,0 +1,7 @@
+-- Description: Pin which sandbox config a session's live sandbox was created on.
+-- NULL means "no live sandbox"; '-' means "the deployment-wide default config".
+-- This is an ephemeral pin that dies with the sandbox, not a permanent owner.
+DO $$ BEGIN RAISE NOTICE '[Migration 000083] Adding sessions.sandbox_config_id'; END $$;
+
+ALTER TABLE sessions ADD COLUMN IF NOT EXISTS sandbox_config_id VARCHAR(36) DEFAULT NULL;
+COMMENT ON COLUMN sessions.sandbox_config_id IS 'Sandbox config the session current live sandbox was created on; NULL = no live sandbox, ''-'' = deployment default';