feat(sandbox): 沙箱后端改为按空间配置,并补齐 E2B 模板与检测诊断
沙箱的后端类型、凭据、模板、超时和私网访问策略此前分散在部署级 WEKNORA_SANDBOX_* 环境变量里,一个实例只能有一套,租户之间无法各用 自己的 E2B 账号或自建 Cube 集群。现在这些配置全部落到空间维度的具名 沙箱配置上:部署环境不再提供覆盖项,未选择配置的智能体直接不启用脚本 执行,而不是静默回落到某个部署默认值——后者会让「这个智能体到底跑在 哪」无从判断。 同时把连接检测从「能不能连上控制面」扩展成可解释的诊断: - E2B 标准模板显式带上 default 标签构建。创建沙箱时裸模板名/ID 只解析 default 标签,构建带了别的标签就永远拿不到,表现为一个与「模板不存在」 无法区分的 404。 - 模板状态不再从历史构建或 spawn 次数反推就绪,只认当前构建;构建完成 却没有 default 标签的模板单独报成 untagged,因为它在列表里和「仍在构建」 长得一样,但等待永远不会有结果。 - 创建失败带上 HTTP 状态,404 走模板解释路径,给出具体到「重建模板」还是 「Key 属于其他团队」的结论。 - 探针脚本改在进程工作目录下暂存。系统临时目录在 macOS 上位于 /var/folders,Docker 虚拟机并不共享,挂载进容器后是空目录,真实技能执行 (脚本在 skills/ 下)却不会踩到,检测因此报假失败。 - 检测失败不再只说「命令输出与预期不符」,带上退出码与 stderr 首行。 前端把沙箱设置页与配置抽屉重做:凭据按「是否已配置」展示而非回显掩码, 删除与停用改为就地确认,占用情况走右侧抽屉,列表卡片展示模板状态、凭据、 超时等可判断健康度的事实。main
parent
95ddeae067
commit
738fe1ec53
65
.env.example
65
.env.example
|
|
@ -569,68 +569,9 @@ SYSTEM_AES_KEY=weknora-system-aes-key-32bytes!!
|
|||
# #####################################################################
|
||||
|
||||
# ========== G1. Agent Skills Sandbox ==========
|
||||
# 以下 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
|
||||
# Sandbox 后端、凭据、模板、超时和私网访问策略全部在「设置 → 沙箱后端」
|
||||
# 按空间维护;部署环境不再提供 WEKNORA_SANDBOX_* 覆盖项。
|
||||
# 多实例仍应配置通用 REDIS_ADDR,以共享 session→sandbox binding。
|
||||
|
||||
# 自定义 Skills 目录(挂载后指定,免重建镜像)。
|
||||
# WEKNORA_SKILLS_DIR=
|
||||
|
|
|
|||
|
|
@ -57,3 +57,6 @@ fix-docker.sh
|
|||
|
||||
# WeChat Mini Program local/private configuration
|
||||
miniprogram/project.private.config.json
|
||||
|
||||
# Staging dir for the Docker sandbox self-check probe (removed after each run)
|
||||
.weknora-sandbox-check-*
|
||||
|
|
|
|||
|
|
@ -312,18 +312,6 @@ services:
|
|||
- WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC=${WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC:-60}
|
||||
- WEKNORA_CHAT_ATTACHMENT_OCR_CONCURRENCY=${WEKNORA_CHAT_ATTACHMENT_OCR_CONCURRENCY:-8}
|
||||
- WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES=${WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES:-8}
|
||||
# Agent Skills Sandbox
|
||||
- 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:-}
|
||||
|
|
|
|||
|
|
@ -122,43 +122,35 @@ type AgentConfig struct {
|
|||
}
|
||||
```
|
||||
|
||||
### Sandbox 配置(环境变量)
|
||||
### Sandbox 配置入口
|
||||
|
||||
下表的环境变量是**部署级默认值**。工作区还可以维护多份具名沙箱后端配置,智能体各自选用其一;未选择的智能体回落到这里的默认值(见「工作区沙箱后端配置」)。
|
||||
|
||||
| 环境变量 | 说明 | 默认值 |
|
||||
|---------|------|--------|
|
||||
| `WEKNORA_SANDBOX_MODE` | sandbox 模式:`docker` / `local` / `cube` / `e2b` / `disabled` | `disabled` |
|
||||
| `WEKNORA_SANDBOX_TIMEOUT` | 脚本执行超时(秒) | `60` |
|
||||
| `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 不再读取 `WEKNORA_SANDBOX_*` 环境变量。后端、凭据、模板、执行超时、TTL 和私网访问策略均在「设置 → 沙箱后端」按空间保存;智能体没有选择空间配置时,脚本执行保持禁用。
|
||||
|
||||
### Sandbox 模式
|
||||
|
||||
Docker、Local、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接检查和智能体选择接口管理。CubeSandbox / E2B 的集群搭建和设置页接入流程见 [WeKnora 沙箱集群与标准模板](sandbox-cluster.md)。设置页会通过当前连接拉取模板目录;若没有 WeKnora 标准模板,后端会从标准镜像发起创建,用户无需复制模板 ID。
|
||||
|
||||
| 模式 | 状态 | 说明 |
|
||||
|------|------|------|
|
||||
| `docker` | 稳定 | 使用 Docker 容器隔离(推荐用于本地/单机部署) |
|
||||
| `local` | 基础 | 本地进程执行(仅基础白名单,无 MicroVM 隔离) |
|
||||
| `docker` | 稳定 | 每次执行启动短生命周期容器;镜像和环境变量按空间配置,不保留会话绑定 |
|
||||
| `local` | 开发 | 直接在 WeKnora 服务主机执行;无容器/MicroVM 隔离,不保留会话绑定 |
|
||||
| `cube` | 稳定 | Tencent CubeSandbox MicroVM;会话级持久,支持多机(需 Redis) |
|
||||
| `e2b` | 稳定 | E2B 云端 MicroVM;会话级持久,支持多机(需 Redis);依赖第三方 SDK go-e2b |
|
||||
| `disabled` | — | 关闭本实例全部沙箱能力,含工作区具名配置 |
|
||||
|
||||
### 工作区沙箱后端配置
|
||||
|
||||
一个工作区可以维护**多份具名**沙箱后端配置(「设置 → 沙箱后端」),智能体在编辑弹窗的「能力扩展 → 沙箱后端」里各自选一份。不选就使用上表的部署级默认后端,行为与本特性上线前完全一致。
|
||||
一个工作区可以维护**多份具名**沙箱后端配置(「设置 → 沙箱后端」),智能体在编辑弹窗的「能力扩展 → 沙箱后端」里各自选一份。不选表示禁用脚本执行。
|
||||
|
||||
同一后端类型可以有多份配置:例如两份 E2B 分别指向不同账号或区域,让不同智能体的技能脚本落在不同配额上。
|
||||
|
||||
**具名配置是自包含的,不继承 `.env`。** 部署级 `WEKNORA_SANDBOX_*` 只服务「没有选择任何具名配置」的智能体;具名配置里留空的字段不会回退到那些值,必须自己填全:
|
||||
**空间配置是唯一运行时来源。** 端点、凭据和运行参数不会从 `.env` 回退:
|
||||
|
||||
| 后端 | 必填 | 可留空 |
|
||||
|---|---|---|
|
||||
| Cube | API 端点、Proxy 端点、沙箱域名、模板 ID | API Key(自建部署通常无鉴权) |
|
||||
| E2B | API Key、模板 ID | API 端点、沙箱域名(go-e2b 自行解析默认值) |
|
||||
| Cube | API 端点、Proxy 端点、沙箱域名、从集群列表选择的模板 | API Key(自建部署通常无鉴权) |
|
||||
| E2B | API Key、从账号列表选择的模板 | API 端点、沙箱域名(go-e2b 自行解析默认值) |
|
||||
|
||||
留空必填项在保存时就会被拒绝(HTTP 400,报文里列出缺哪些字段),而不是等到第一次执行技能才失败。HTTP 超时与沙箱 TTL 留空走**内置默认值**,同样不看 `.env`。唯一仍沿用部署值的是「执行超时」,因为它属于运维护栏而非后端身份。
|
||||
留空必填项在保存时就会被拒绝(HTTP 400)。HTTP 超时、沙箱 TTL 和执行超时留空均使用程序内置默认值。
|
||||
|
||||
这条规则换来的是:库里那一行就是沙箱位置的完整描述。因此身份比较不必再去解析 `.env`,改 `.env` 也不会在无人察觉的情况下把某份配置重新指向别的账号。
|
||||
|
||||
|
|
@ -180,16 +172,16 @@ type AgentConfig struct {
|
|||
| 值 | 含义 |
|
||||
|---|---|
|
||||
| `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`。
|
||||
- **binding store 自动选择**:进程根据通用 `REDIS_ADDR` 是否配置自动决定绑定存储;Redis key 命名空间复用 `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 删除。
|
||||
- **切换 provider**:不同 provider 的 sandbox ID 不通用。智能体改选配置只影响之后新建的沙箱,已有沙箱继续按 session pin 回收。
|
||||
- **⚠️ 孤儿沙箱不会被 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 都实现了同一契约。
|
||||
|
||||
|
|
@ -698,4 +690,4 @@ go run ./cmd/skills-demo/main.go
|
|||
- `skill name too long`: 名称超过 50 字符
|
||||
- `skill name contains invalid characters`: 包含非法字符
|
||||
- `skill name is reserved`: 使用了保留词
|
||||
- `skill description too long`: 描述超过 500 字符
|
||||
- `skill description too long`: 描述超过 500 字符
|
||||
|
|
|
|||
|
|
@ -0,0 +1,58 @@
|
|||
# WeKnora 沙箱集群与标准模板
|
||||
|
||||
本文面向部署和平台管理员,说明如何把 CubeSandbox 或 E2B 接入 WeKnora。Docker、Local、CubeSandbox、E2B 都在同一个空间设置页面通过同一套配置与检查接口管理;只有远端后端需要本文所述的集群和模板准备。普通智能体使用者不需要搭建模板,也不应该逐项猜测运行环境。
|
||||
|
||||
## 谁负责什么
|
||||
|
||||
| 角色 | 职责 |
|
||||
| --- | --- |
|
||||
| WeKnora 发布流程 | 维护 `docker/Dockerfile.sandbox`,发布与 WeKnora 版本匹配的 `wechatopenai/weknora-sandbox` 镜像 |
|
||||
| 集群管理员 | 部署 CubeSandbox 或开通 E2B,并保证控制面模板 API 可用 |
|
||||
| 空间管理员 | 在“设置 → 沙箱后端”中填写集群地址和凭据,先完成连接验证,再选择接口返回的模板 |
|
||||
| 智能体管理员 | 在智能体的 Skills 配置中选择已经验证过的沙箱后端 |
|
||||
|
||||
“WeKnora 标准模板”指模板内容由 WeKnora 维护,并不代表所有集群共享同一个模板 ID。CubeSandbox 的模板 ID、E2B 的模板 ID/别名都属于具体集群或账号;跨集群硬编码一个 ID 会指向不存在或内容不一致的模板。
|
||||
|
||||
## 标准模板包含什么
|
||||
|
||||
标准镜像定义在 `docker/Dockerfile.sandbox`,当前包含:
|
||||
|
||||
- Python 3.11;
|
||||
- Node.js 20、npm 与 npx;
|
||||
- jq 及基础 Shell 工具;
|
||||
- `/workspace` 工作目录;
|
||||
- UID 1000 的非 root `sandbox` 用户。
|
||||
|
||||
生产环境应使用与 WeKnora 相同的版本标签,不建议长期指向 `latest`。Skills 新增系统依赖时,应先更新标准镜像并重新注册模板,再切换集群的默认模板 ID。
|
||||
|
||||
## CubeSandbox
|
||||
|
||||
1. 按 [CubeSandbox Quick Start](https://github.com/TencentCloud/CubeSandbox/blob/master/docs/guide/quickstart.md) 完成控制面、计算节点、CubeProxy 和域名解析配置。生产环境还需要按官方文档完成鉴权、TLS、网络策略和多节点部署。
|
||||
2. 在 WeKnora 的空间设置中填写 CubeAPI、CubeProxy、sandbox domain 和可选 API Key。若这些端点位于 RFC1918/loopback 网络,显式打开“允许访问私网集群地址”。
|
||||
3. 点击“连接并继续”。WeKnora 先验证控制面地址与凭据,通过后才进入模板步骤并调用集群模板列表;如果不存在名为 `weknora` 的标准模板,会从 `wechatopenai/weknora-sandbox:latest` 发起一次构建。
|
||||
4. 模板构建状态会自动刷新。状态变为 `READY` 后才可选择并进入运行配置;界面显示模板名称、状态和版本,配置内部才保存该集群自己的 `template_id`。
|
||||
|
||||
多实例 WeKnora 必须配置 Redis,以共享 session 到 sandbox 的绑定。只有单实例开发环境才应使用内存绑定。
|
||||
|
||||
## E2B
|
||||
|
||||
E2B 官方托管服务和自建 E2B Infrastructure 都可接入。填写 API Key 后先执行“连接并继续”,流程与 Cube 相同:验证连接后列出账号可见模板,缺少 `weknora` 时通过 E2B Template API 从标准镜像启动后台构建。自建部署还需填写 API URL 和 sandbox domain;E2B 上游通过 Terraform 提供 AWS、GCP 等部署方式,具体以 [E2B self-hosting guide](https://github.com/e2b-dev/infra/blob/main/self-host.md) 和 [E2B Template 文档](https://e2b.dev/docs/template/quickstart) 为准。
|
||||
|
||||
## 在设置页面完成接入
|
||||
|
||||
1. 打开“设置 → 沙箱后端”,点击“添加沙箱后端”。
|
||||
2. 填写该集群自己的 API、Proxy、sandbox domain 和凭据;这些值只保存在当前空间配置中,不读取 Sandbox 环境变量。
|
||||
3. 点击“连接并继续”,验证控制面地址和凭据;连接通过后才加载模板列表。
|
||||
4. 等待自动创建的标准模板就绪,或选择集群已有的兼容模板;构建中的模板不可选择,状态会自动刷新。
|
||||
5. 配置运行参数;上线前可执行一次“完整验证”。完整验证会真实创建、执行并销毁一个沙箱。
|
||||
6. 保存后,在智能体 Skills 配置中选择该后端。对配置的修改只影响之后新建的沙箱;已有会话仍固定使用创建时的配置。
|
||||
|
||||
## 上线检查
|
||||
|
||||
- 模板版本与 WeKnora 版本匹配,且不依赖浮动的 `latest`;
|
||||
- WeKnora 到控制面、Proxy 和 sandbox domain 的 DNS、TLS 与防火墙均已打通;
|
||||
- 多实例部署已配置 Redis;
|
||||
- API Key 只通过密钥管理或加密配置保存;
|
||||
- “连接验证”和“完整验证”均通过;
|
||||
- 已配置运行中与 paused 沙箱的容量监控、费用监控和孤儿清理;
|
||||
- 切换模板或集群前已确认旧会话和旧沙箱的回收策略。
|
||||
|
|
@ -74,15 +74,9 @@ my-skill/
|
|||
|
||||
执行前进行多层安全校验:危险命令检测、危险模式匹配、网络访问检测、反向 Shell 检测、参数注入检测等。
|
||||
|
||||
### Sandbox 模式
|
||||
### Sandbox 配置
|
||||
|
||||
| 模式 | 说明 |
|
||||
|------|------|
|
||||
| `docker` | 使用 Docker 容器隔离(推荐) |
|
||||
| `local` | 本地进程执行(基础安全限制) |
|
||||
| `disabled` | 禁用脚本执行 |
|
||||
|
||||
通过环境变量 `WEKNORA_SANDBOX_MODE` 配置。
|
||||
空间管理员在「设置 → 沙箱后端」中统一维护 Docker、Local、CubeSandbox 或 E2B 配置。远端模板从目标集群实时获取;缺少 WeKnora 标准模板时由系统自动创建。智能体在编辑页选择一份空间配置,没有选择时不执行技能脚本。Docker/Local 每次独立执行,CubeSandbox/E2B 则保留会话级沙箱。
|
||||
|
||||
## 配置示例
|
||||
|
||||
|
|
|
|||
|
|
@ -703,6 +703,7 @@ export interface SandboxE2BConfig {
|
|||
export interface SandboxConfig {
|
||||
sandbox_type?: string
|
||||
default_timeout_sec?: number
|
||||
allow_private_endpoints?: boolean
|
||||
env_vars?: Record<string, string>
|
||||
volume_mount?: SandboxVolumeMountConfig
|
||||
cube?: SandboxCubeConfig
|
||||
|
|
@ -715,6 +716,8 @@ export interface SandboxCheckItem {
|
|||
name: string
|
||||
ok: boolean | null
|
||||
message?: string
|
||||
/** Stable code for why a probe was skipped; localized by the caller. */
|
||||
reason?: string
|
||||
latency_ms?: number
|
||||
}
|
||||
|
||||
|
|
@ -725,23 +728,21 @@ export interface SandboxCheckResult {
|
|||
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 SandboxTemplate {
|
||||
id: string
|
||||
name: string
|
||||
status?: string
|
||||
version?: string
|
||||
image?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
standard: boolean
|
||||
}
|
||||
|
||||
export interface SandboxConfigDefaults {
|
||||
sandbox_type: string
|
||||
default_timeout_sec?: number
|
||||
docker_image?: string
|
||||
cube?: SandboxProviderDefaults
|
||||
e2b?: SandboxProviderDefaults
|
||||
export interface SandboxTemplateCatalog {
|
||||
templates: SandboxTemplate[]
|
||||
standard_template_id?: string
|
||||
provisioned: boolean
|
||||
}
|
||||
|
||||
/** One named sandbox backend config. Credentials arrive masked. */
|
||||
|
|
@ -777,26 +778,20 @@ export interface SandboxInventory {
|
|||
unverifiable?: boolean
|
||||
}
|
||||
|
||||
/** Named sandbox backends that support per-config credentials (cube/e2b only). */
|
||||
export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b'] as const
|
||||
/** Sandbox backends managed as named workspace configurations. */
|
||||
export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b', 'docker', 'local'] 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.
|
||||
*/
|
||||
/** Returns every sandbox config of the workspace. No config means 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
|
||||
}>
|
||||
}
|
||||
|
|
@ -848,6 +843,21 @@ export function getSandboxConfigInventory(id: string): Promise<{ data: SandboxIn
|
|||
}>
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch templates using the connection currently entered in the drawer.
|
||||
* `ensure_standard` starts a provider-side build when no WeKnora template is
|
||||
* present; the returned building item can be polled through the same endpoint.
|
||||
*/
|
||||
export function querySandboxTemplates(payload: {
|
||||
config: SandboxConfig
|
||||
config_id?: string
|
||||
ensure_standard?: boolean
|
||||
}): Promise<{ data: SandboxTemplateCatalog }> {
|
||||
return post('/api/v1/sandbox-configs/templates/query', payload) as unknown as Promise<{
|
||||
data: SandboxTemplateCatalog
|
||||
}>
|
||||
}
|
||||
|
||||
/**
|
||||
* Probe a sandbox configuration without saving it. Redacted secrets are
|
||||
* resolved server-side, so pass `config_id` alongside an edited `config` to
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Docker</title><path d="M13.983 11.078h2.119a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.119a.185.185 0 00-.185.185v1.888c0 .102.083.185.185.185m-2.954-5.43h2.118a.186.186 0 00.186-.186V3.574a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m0 2.716h2.118a.187.187 0 00.186-.186V6.29a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.887c0 .102.082.185.185.186m-2.93 0h2.12a.186.186 0 00.184-.186V6.29a.185.185 0 00-.185-.185H8.1a.185.185 0 00-.185.185v1.887c0 .102.083.185.185.186m-2.964 0h2.119a.186.186 0 00.185-.186V6.29a.185.185 0 00-.185-.185H5.136a.186.186 0 00-.186.185v1.887c0 .102.084.185.186.186m5.893 2.715h2.118a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m-2.93 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.083.185.185.185m-2.964 0h2.119a.185.185 0 00.185-.185V9.006a.185.185 0 00-.184-.186h-2.12a.186.186 0 00-.186.186v1.887c0 .102.084.185.186.185m-2.92 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.082.185.185.185M23.763 9.89c-.065-.051-.672-.51-1.954-.51-.338.001-.676.03-1.01.087-.248-1.7-1.653-2.53-1.716-2.566l-.344-.199-.226.327c-.284.438-.49.922-.612 1.43-.23.97-.09 1.882.403 2.661-.595.332-1.55.413-1.744.42H.751a.751.751 0 00-.75.748 11.376 11.376 0 00.692 4.062c.545 1.428 1.355 2.48 2.41 3.124 1.18.723 3.1 1.137 5.275 1.137.983.003 1.963-.086 2.93-.266a12.248 12.248 0 003.823-1.389c.98-.567 1.86-1.288 2.61-2.136 1.252-1.418 1.998-2.997 2.553-4.4h.221c1.372 0 2.215-.549 2.68-1.009.309-.293.55-.65.707-1.046l.098-.288Z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,99 @@
|
|||
<template>
|
||||
<span class="sandbox-badge" :class="badgeClass" :style="badgeStyle" :aria-hidden="true">
|
||||
<t-icon v-if="!logo" :name="iconName" />
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { providerLogo } from '@/views/settings/providerLogos'
|
||||
|
||||
// The sandbox list and the config drawer must show the same mark for a backend,
|
||||
// so both render this badge instead of each mapping types to icons themselves.
|
||||
// Vendors we ship a logo for (Docker) win over the generic TDesign glyphs.
|
||||
const props = withDefaults(defineProps<{
|
||||
type: string
|
||||
size?: 'sm' | 'md'
|
||||
}>(), { size: 'md' })
|
||||
|
||||
const logo = computed(() => providerLogo('sandbox', props.type))
|
||||
|
||||
const iconName = computed(() => {
|
||||
if (props.type === 'cube' || props.type === 'local') return 'server'
|
||||
if (props.type === 'disabled') return 'minus-circle'
|
||||
return 'cloud'
|
||||
})
|
||||
|
||||
const badgeClass = computed(() => [
|
||||
`sandbox-badge--${props.type}`,
|
||||
`sandbox-badge--${props.size}`,
|
||||
{ 'sandbox-badge--mono': logo.value?.mode === 'mono' },
|
||||
])
|
||||
|
||||
const badgeStyle = computed((): Record<string, string> => (
|
||||
logo.value?.mode === 'mono' ? { '--logo-url': `url("${logo.value.url}")` } : {}
|
||||
))
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.sandbox-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
border-radius: 9px;
|
||||
background: rgba(0, 82, 217, 0.1);
|
||||
color: #0052d9;
|
||||
}
|
||||
|
||||
.sandbox-badge--md {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.sandbox-badge--sm {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 7px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.sandbox-badge--e2b {
|
||||
background: rgba(98, 53, 187, 0.1);
|
||||
color: #6235bb;
|
||||
}
|
||||
|
||||
.sandbox-badge--docker {
|
||||
background: rgba(29, 99, 237, 0.1);
|
||||
color: #1d63ed;
|
||||
}
|
||||
|
||||
.sandbox-badge--local {
|
||||
background: rgba(17, 128, 83, 0.1);
|
||||
color: #118053;
|
||||
}
|
||||
|
||||
.sandbox-badge--mono::before {
|
||||
content: '';
|
||||
background-color: currentColor;
|
||||
-webkit-mask-image: var(--logo-url);
|
||||
-webkit-mask-position: center;
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
-webkit-mask-size: contain;
|
||||
mask-image: var(--logo-url);
|
||||
mask-position: center;
|
||||
mask-repeat: no-repeat;
|
||||
mask-size: contain;
|
||||
}
|
||||
|
||||
.sandbox-badge--md.sandbox-badge--mono::before {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
.sandbox-badge--sm.sandbox-badge--mono::before {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1017,10 +1017,10 @@ export default {
|
|||
sandboxConfig: 'Sandbox backend',
|
||||
sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
|
||||
sandboxBackend: 'Sandbox backend',
|
||||
sandboxBackendDefault: 'Use deployment defaults',
|
||||
sandboxBackendDefault: 'Disable sandbox',
|
||||
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.',
|
||||
sandboxNoConfigs: 'This workspace has no sandbox backend yet, so skill scripts will not run. 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?',
|
||||
|
|
@ -1055,18 +1055,34 @@ export default {
|
|||
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.',
|
||||
description: 'Manage the sandbox runtimes used by agent skills. Each agent can select one workspace backend.',
|
||||
editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',
|
||||
stepConnection: 'Connect',
|
||||
stepTemplate: 'Template',
|
||||
stepRuntime: 'Runtime',
|
||||
setupProgress: 'Sandbox setup progress',
|
||||
stepDescriptions: {
|
||||
connection: 'Configure the backend and verify the connection before loading templates.',
|
||||
template: 'Choose a ready template returned by the connected cluster.',
|
||||
runtime: 'Configure execution settings and environment variables, then save.',
|
||||
},
|
||||
back: 'Back',
|
||||
connectAndContinue: 'Connect and continue',
|
||||
loading: 'Loading sandbox configuration...',
|
||||
loadFailed: 'Failed to load sandbox configuration',
|
||||
backend: 'Sandbox backend',
|
||||
backendHint: 'Leave unset to inherit the global default',
|
||||
backendType: 'Sandbox type',
|
||||
backendTypePlaceholder: 'Select a sandbox type',
|
||||
scriptPolicyLabel: 'Allow skill scripts to run in sandboxes',
|
||||
scriptPolicyDesc: 'When off, agents in this workspace can only read skill content. Remote sandboxes already running are released once their sessions end.',
|
||||
backendDescriptions: {
|
||||
cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',
|
||||
e2b: 'Managed MicroVM service or an E2B-compatible deployment',
|
||||
docker: 'Run every script in a short-lived container on this WeKnora host',
|
||||
local: 'Run scripts directly in the WeKnora server process environment',
|
||||
},
|
||||
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',
|
||||
viewClusterGuide: 'Cluster setup guide',
|
||||
configName: 'Config name',
|
||||
configNamePlaceholder: 'e.g. Production E2B',
|
||||
configNameRequired: 'Please enter a config name',
|
||||
|
|
@ -1074,10 +1090,17 @@ export default {
|
|||
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.',
|
||||
sectionBasic: 'Basic information',
|
||||
sectionConnection: 'Cluster connection',
|
||||
sectionRuntimeEnvironment: 'Runtime environment',
|
||||
sectionTemplate: 'Runtime template',
|
||||
sectionRuntime: 'Execution settings',
|
||||
sectionEnvironment: 'Environment variables',
|
||||
noConfigs: 'No sandbox backend yet. Agents without a workspace configuration will not run skill scripts.',
|
||||
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',
|
||||
inventoryDrawerDesc: 'Sandboxes this config still holds, plus the sessions and agents affected.',
|
||||
inventoryFailed: 'Failed to load sandbox usage',
|
||||
sandboxCount: 'Sandboxes',
|
||||
sandboxCountUnknown: 'Unknown (backend unreachable)',
|
||||
|
|
@ -1103,9 +1126,60 @@ export default {
|
|||
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.',
|
||||
namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',
|
||||
weknoraTemplateTitle: 'WeKnora standard template',
|
||||
weknoraDockerImage: 'WeKnora standard image',
|
||||
weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',
|
||||
localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',
|
||||
weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',
|
||||
weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',
|
||||
recommendedTag: 'Recommended',
|
||||
cardTemplateConfigured: 'Template configured',
|
||||
cardCredentialMissing: 'API key missing',
|
||||
cardTimeout: 'Timeout {sec}s',
|
||||
cardTtl: 'Sandbox TTL {sec}s',
|
||||
cardVolumeMounted: 'Volume mounted',
|
||||
cardEnvVars: '{count} env vars',
|
||||
cardPrivateEndpoints: 'Private endpoints allowed',
|
||||
templateNotConfigured: 'Template not configured',
|
||||
imageNotConfigured: 'Image not configured',
|
||||
localRuntimeSummary: 'WeKnora server process',
|
||||
templateApplied: 'Applied',
|
||||
refreshTemplates: 'Refresh templates',
|
||||
templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',
|
||||
templateSelectPlaceholder: 'Connect to the cluster to load templates',
|
||||
templateLoadHint: 'Enter the cluster connection and refresh. WeKnora creates its standard template when missing.',
|
||||
templateLoadFailed: 'Failed to load templates',
|
||||
standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',
|
||||
templateNotReady: 'The selected template is not ready. Refresh and wait for the build to finish.',
|
||||
connectionPassed: 'Connection verified. Templates below are loaded from this cluster.',
|
||||
connectionPassedTitle: 'Cluster connected',
|
||||
templateStepHint: 'WeKnora automatically creates its standard template when missing. You can continue after a template is ready.',
|
||||
loadingTemplates: 'Loading templates from the cluster...',
|
||||
templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',
|
||||
templateUntaggedHint: 'The builds finished but none carries the default tag, so sandbox creation cannot resolve this template. Delete it in E2B and refresh; WeKnora will rebuild it.',
|
||||
noTemplates: 'No templates were returned by this cluster.',
|
||||
templateReadyHint: 'Template “{name}” is ready and selected.',
|
||||
templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',
|
||||
templateStatuses: {
|
||||
ready: 'Ready',
|
||||
building: 'Building',
|
||||
untagged: 'No default tag',
|
||||
failed: 'Failed',
|
||||
unknown: 'Unknown',
|
||||
},
|
||||
allowPrivateEndpoints: 'Allow private cluster endpoints',
|
||||
allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',
|
||||
howToBuildTemplate: 'Sandbox cluster setup and template guide',
|
||||
noEnvVars: 'No additional environment variables. Add only values required by skills.',
|
||||
fieldRequired: 'Required',
|
||||
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
|
||||
cubeApiKeyWhere: 'How to enable auth on a self-hosted cluster',
|
||||
e2bApiKeyHelp: 'Create one on the API Keys page of the E2B dashboard; it usually starts with e2b_.',
|
||||
e2bApiKeyWhere: 'Get an API key from the E2B dashboard',
|
||||
apiKeyPlaceholder: 'Paste the API key',
|
||||
secretConfigured: 'Key configured (not shown again); enter a new value to rotate',
|
||||
secretKeepHint: 'Configured — leave empty to keep it',
|
||||
e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
|
||||
e2bDomainOptional: 'Optional — the SDK default is used when empty',
|
||||
backends: {
|
||||
|
|
@ -1121,9 +1195,12 @@ export default {
|
|||
apiKey: 'API key',
|
||||
templateId: 'Template ID',
|
||||
httpTimeout: 'HTTP timeout (s)',
|
||||
httpTimeoutHelp: 'How long a management call to the backend may take before the endpoint counts as unreachable. Empty means 30 seconds.',
|
||||
sandboxTtl: 'Sandbox TTL (s)',
|
||||
sandboxTtlHelp: 'How long an idle sandbox survives before the provider reclaims it. Too short and a resumed session has to rebuild it; too long and idle instances keep billing. Empty means the backend default.',
|
||||
dockerImage: 'Docker image',
|
||||
defaultTimeout: 'Execution timeout (s)',
|
||||
defaultTimeoutHelp: 'Longest a single skill script may run before it is killed. Empty means 60 seconds.',
|
||||
envVars: 'Environment variables',
|
||||
envKey: 'Name',
|
||||
envValue: 'Value',
|
||||
|
|
@ -1135,11 +1212,24 @@ export default {
|
|||
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?',
|
||||
recheck: 'Verify again',
|
||||
deepCheckIntro: 'Before saving you can run a full verification: it creates a throwaway sandbox, runs one script, checks outbound access and destroys it.',
|
||||
deepCheckConfirm: 'Full verification runs a throwaway script. Remote backends also create and destroy a real sandbox and may consume a small amount of sandbox time. Continue?',
|
||||
checkPassed: 'All checks passed',
|
||||
checkFailed: 'Some checks failed',
|
||||
checkScopeConnection: 'Only the control plane was verified: the endpoint responds and the credential is valid. Whether a script actually runs is still unverified.',
|
||||
checkScopeFull: 'Endpoint, credential, template, in-sandbox execution and outbound network were all verified for real.',
|
||||
checkPendingHint: '{names} can only be confirmed by a full verification, which creates a throwaway sandbox, runs one script and destroys it.',
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
skipReasons: {
|
||||
needs_deep_check: 'Needs full verification',
|
||||
control_plane_unreachable: 'Skipped: control plane unreachable',
|
||||
environment_unavailable: 'Skipped: runtime unavailable',
|
||||
sandbox_not_created: 'Skipped: sandbox was not created',
|
||||
sandbox_exec_failed: 'Skipped: in-sandbox execution failed',
|
||||
},
|
||||
checks: {
|
||||
environment_available: 'Runtime availability',
|
||||
client_build: 'Client construction',
|
||||
api_url_reachable: 'Endpoint reachability',
|
||||
credential_valid: 'Credential validity',
|
||||
|
|
|
|||
|
|
@ -4655,18 +4655,34 @@ export default {
|
|||
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.',
|
||||
description: 'Manage the sandbox runtimes used by agent skills. Each agent can select one workspace backend.',
|
||||
editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',
|
||||
stepConnection: 'Connect',
|
||||
stepTemplate: 'Template',
|
||||
stepRuntime: 'Runtime',
|
||||
setupProgress: 'Sandbox setup progress',
|
||||
stepDescriptions: {
|
||||
connection: 'Configure the backend and verify the connection before loading templates.',
|
||||
template: 'Choose a ready template returned by the connected cluster.',
|
||||
runtime: 'Configure execution settings and environment variables, then save.',
|
||||
},
|
||||
back: 'Back',
|
||||
connectAndContinue: 'Connect and continue',
|
||||
loading: 'Loading sandbox configuration...',
|
||||
loadFailed: 'Failed to load sandbox configuration',
|
||||
backend: 'Sandbox backend',
|
||||
backendHint: 'Leave unset to inherit the global default',
|
||||
backendType: '샌드박스 유형',
|
||||
backendTypePlaceholder: '샌드박스 유형 선택',
|
||||
scriptPolicyLabel: '샌드박스에서 스킬 스크립트 실행 허용',
|
||||
scriptPolicyDesc: '끄면 이 워크스페이스의 에이전트는 스킬 내용만 읽을 수 있습니다. 이미 실행 중인 원격 샌드박스는 해당 세션이 종료된 후 해제됩니다.',
|
||||
backendDescriptions: {
|
||||
cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',
|
||||
e2b: 'Managed MicroVM service or an E2B-compatible deployment',
|
||||
docker: 'Run every script in a short-lived container on this WeKnora host',
|
||||
local: 'Run scripts directly in the WeKnora server process environment',
|
||||
},
|
||||
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',
|
||||
viewClusterGuide: 'Cluster setup guide',
|
||||
configName: 'Config name',
|
||||
configNamePlaceholder: 'e.g. Production E2B',
|
||||
configNameRequired: 'Please enter a config name',
|
||||
|
|
@ -4674,10 +4690,17 @@ export default {
|
|||
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.',
|
||||
sectionBasic: 'Basic information',
|
||||
sectionConnection: 'Cluster connection',
|
||||
sectionRuntimeEnvironment: 'Runtime environment',
|
||||
sectionTemplate: 'Runtime template',
|
||||
sectionRuntime: 'Execution settings',
|
||||
sectionEnvironment: 'Environment variables',
|
||||
noConfigs: 'No sandbox backend yet. Agents without a workspace configuration will not run skill scripts.',
|
||||
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',
|
||||
inventoryDrawerDesc: '이 설정이 아직 점유한 샌드박스와 영향을 받는 세션·에이전트입니다.',
|
||||
inventoryFailed: 'Failed to load sandbox usage',
|
||||
sandboxCount: 'Sandboxes',
|
||||
sandboxCountUnknown: 'Unknown (backend unreachable)',
|
||||
|
|
@ -4703,9 +4726,60 @@ export default {
|
|||
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.',
|
||||
namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',
|
||||
weknoraTemplateTitle: 'WeKnora standard template',
|
||||
weknoraDockerImage: 'WeKnora standard image',
|
||||
weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',
|
||||
localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',
|
||||
weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',
|
||||
weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',
|
||||
recommendedTag: 'Recommended',
|
||||
templateNotConfigured: 'Template not configured',
|
||||
cardTemplateConfigured: '템플릿 설정됨',
|
||||
cardCredentialMissing: 'API 키 없음',
|
||||
cardTimeout: '타임아웃 {sec}초',
|
||||
cardTtl: '샌드박스 유지 {sec}초',
|
||||
cardVolumeMounted: '볼륨 마운트됨',
|
||||
cardEnvVars: '환경 변수 {count}개',
|
||||
cardPrivateEndpoints: '사설망 접근 허용',
|
||||
imageNotConfigured: 'Image not configured',
|
||||
localRuntimeSummary: 'WeKnora server process',
|
||||
templateApplied: 'Applied',
|
||||
refreshTemplates: 'Refresh templates',
|
||||
templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',
|
||||
templateSelectPlaceholder: 'Connect to the cluster to load templates',
|
||||
templateLoadHint: 'Enter the cluster connection and refresh. WeKnora creates its standard template when missing.',
|
||||
templateLoadFailed: 'Failed to load templates',
|
||||
standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',
|
||||
templateNotReady: 'The selected template is not ready. Refresh and wait for the build to finish.',
|
||||
connectionPassed: 'Connection verified. Templates below are loaded from this cluster.',
|
||||
connectionPassedTitle: 'Cluster connected',
|
||||
templateStepHint: 'WeKnora automatically creates its standard template when missing. You can continue after a template is ready.',
|
||||
loadingTemplates: 'Loading templates from the cluster...',
|
||||
templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',
|
||||
templateUntaggedHint: '빌드는 끝났지만 default 태그가 붙은 빌드가 없어 샌드박스 생성 시 이 템플릿을 찾을 수 없습니다. E2B에서 템플릿을 삭제하고 새로고침하면 WeKnora가 다시 빌드합니다.',
|
||||
noTemplates: 'No templates were returned by this cluster.',
|
||||
templateReadyHint: 'Template “{name}” is ready and selected.',
|
||||
templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',
|
||||
templateStatuses: {
|
||||
ready: 'Ready',
|
||||
building: 'Building',
|
||||
untagged: 'default 태그 없음',
|
||||
failed: 'Failed',
|
||||
unknown: 'Unknown',
|
||||
},
|
||||
allowPrivateEndpoints: 'Allow private cluster endpoints',
|
||||
allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',
|
||||
howToBuildTemplate: 'Sandbox cluster setup and template guide',
|
||||
noEnvVars: 'No additional environment variables. Add only values required by skills.',
|
||||
fieldRequired: 'Required',
|
||||
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
|
||||
cubeApiKeyWhere: '자체 호스팅 클러스터에서 인증을 켜는 방법',
|
||||
e2bApiKeyHelp: 'E2B 대시보드의 API Keys 페이지에서 생성하며 보통 e2b_ 로 시작합니다.',
|
||||
e2bApiKeyWhere: 'E2B 대시보드에서 API 키 발급받기',
|
||||
apiKeyPlaceholder: 'API 키를 붙여넣으세요',
|
||||
secretConfigured: '키가 설정되어 있습니다(다시 표시되지 않음). 새 값을 입력하면 교체됩니다',
|
||||
secretKeepHint: '설정됨 — 비워 두면 변경되지 않습니다',
|
||||
e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
|
||||
e2bDomainOptional: 'Optional — the SDK default is used when empty',
|
||||
backends: {
|
||||
|
|
@ -4721,9 +4795,12 @@ export default {
|
|||
apiKey: 'API key',
|
||||
templateId: 'Template ID',
|
||||
httpTimeout: 'HTTP timeout (s)',
|
||||
httpTimeoutHelp: '백엔드 관리 API 호출을 기다리는 상한입니다. 초과하면 엔드포인트를 사용할 수 없는 것으로 간주합니다. 비워 두면 30초입니다.',
|
||||
sandboxTtl: 'Sandbox TTL (s)',
|
||||
sandboxTtlHelp: '유휴 샌드박스가 회수되기까지의 시간입니다. 너무 짧으면 세션을 이어갈 때 다시 만들어야 하고, 너무 길면 유휴 인스턴스에 계속 요금이 발생합니다. 비워 두면 백엔드 기본값을 사용합니다.',
|
||||
dockerImage: 'Docker image',
|
||||
defaultTimeout: 'Execution timeout (s)',
|
||||
defaultTimeoutHelp: '스킬 스크립트 한 번이 실행될 수 있는 최대 시간이며, 초과하면 강제 종료됩니다. 비워 두면 60초입니다.',
|
||||
envVars: 'Environment variables',
|
||||
envKey: 'Name',
|
||||
envValue: 'Value',
|
||||
|
|
@ -4735,11 +4812,24 @@ export default {
|
|||
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?',
|
||||
recheck: '다시 검증',
|
||||
deepCheckIntro: '저장하기 전에 전체 검증을 한 번 실행할 수 있습니다. 임시 샌드박스를 만들어 스크립트를 실행하고 외부 통신까지 확인한 뒤 삭제합니다.',
|
||||
deepCheckConfirm: 'Full verification runs a throwaway script. Remote backends also create and destroy a real sandbox and may consume a small amount of sandbox time. Continue?',
|
||||
checkPassed: 'All checks passed',
|
||||
checkFailed: 'Some checks failed',
|
||||
checkScopeConnection: '이번에는 컨트롤 플레인만 확인했습니다. 엔드포인트는 응답하고 자격 증명도 유효하지만, 스크립트가 실제로 실행되는지는 아직 확인되지 않았습니다.',
|
||||
checkScopeFull: '엔드포인트, 자격 증명, 템플릿, 샌드박스 내 실행, 외부 통신까지 모두 실제로 검증했습니다.',
|
||||
checkPendingHint: '{names}은(는) 전체 검증으로만 확인할 수 있습니다. 임시 샌드박스를 실제로 만들어 스크립트를 한 번 실행한 뒤 삭제합니다.',
|
||||
skipReasons: {
|
||||
needs_deep_check: '전체 검증 필요',
|
||||
control_plane_unreachable: '컨트롤 플레인에 연결할 수 없어 건너뜀',
|
||||
environment_unavailable: '실행 환경을 사용할 수 없어 건너뜀',
|
||||
sandbox_not_created: '샌드박스가 생성되지 않아 건너뜀',
|
||||
sandbox_exec_failed: '샌드박스 내 실행 실패로 건너뜀',
|
||||
},
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
checks: {
|
||||
environment_available: 'Runtime availability',
|
||||
client_build: 'Client construction',
|
||||
api_url_reachable: 'Endpoint reachability',
|
||||
credential_valid: 'Credential validity',
|
||||
|
|
@ -5145,10 +5235,10 @@ export default {
|
|||
sandboxConfig: 'Sandbox backend',
|
||||
sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
|
||||
sandboxBackend: 'Sandbox backend',
|
||||
sandboxBackendDefault: 'Use deployment defaults',
|
||||
sandboxBackendDefault: 'Disable sandbox',
|
||||
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.',
|
||||
sandboxNoConfigs: 'This workspace has no sandbox backend yet, so skill scripts will not run. 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란 무엇인가요?',
|
||||
|
|
|
|||
|
|
@ -4655,18 +4655,34 @@ export default {
|
|||
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.',
|
||||
description: 'Manage the sandbox runtimes used by agent skills. Each agent can select one workspace backend.',
|
||||
editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',
|
||||
stepConnection: 'Connect',
|
||||
stepTemplate: 'Template',
|
||||
stepRuntime: 'Runtime',
|
||||
setupProgress: 'Sandbox setup progress',
|
||||
stepDescriptions: {
|
||||
connection: 'Configure the backend and verify the connection before loading templates.',
|
||||
template: 'Choose a ready template returned by the connected cluster.',
|
||||
runtime: 'Configure execution settings and environment variables, then save.',
|
||||
},
|
||||
back: 'Back',
|
||||
connectAndContinue: 'Connect and continue',
|
||||
loading: 'Loading sandbox configuration...',
|
||||
loadFailed: 'Failed to load sandbox configuration',
|
||||
backend: 'Sandbox backend',
|
||||
backendHint: 'Leave unset to inherit the global default',
|
||||
backendType: 'Тип песочницы',
|
||||
backendTypePlaceholder: 'Выберите тип песочницы',
|
||||
scriptPolicyLabel: 'Разрешить выполнение скриптов навыков в песочницах',
|
||||
scriptPolicyDesc: 'Если выключено, агенты этого пространства смогут только читать содержимое навыков. Уже запущенные удалённые песочницы освободятся после завершения их сессий.',
|
||||
backendDescriptions: {
|
||||
cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',
|
||||
e2b: 'Managed MicroVM service or an E2B-compatible deployment',
|
||||
docker: 'Run every script in a short-lived container on this WeKnora host',
|
||||
local: 'Run scripts directly in the WeKnora server process environment',
|
||||
},
|
||||
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',
|
||||
viewClusterGuide: 'Cluster setup guide',
|
||||
configName: 'Config name',
|
||||
configNamePlaceholder: 'e.g. Production E2B',
|
||||
configNameRequired: 'Please enter a config name',
|
||||
|
|
@ -4674,10 +4690,17 @@ export default {
|
|||
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.',
|
||||
sectionBasic: 'Basic information',
|
||||
sectionConnection: 'Cluster connection',
|
||||
sectionRuntimeEnvironment: 'Runtime environment',
|
||||
sectionTemplate: 'Runtime template',
|
||||
sectionRuntime: 'Execution settings',
|
||||
sectionEnvironment: 'Environment variables',
|
||||
noConfigs: 'No sandbox backend yet. Agents without a workspace configuration will not run skill scripts.',
|
||||
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',
|
||||
inventoryDrawerDesc: 'Песочницы, которые всё ещё занимает эта конфигурация, а также затронутые сессии и агенты.',
|
||||
inventoryFailed: 'Failed to load sandbox usage',
|
||||
sandboxCount: 'Sandboxes',
|
||||
sandboxCountUnknown: 'Unknown (backend unreachable)',
|
||||
|
|
@ -4703,9 +4726,60 @@ export default {
|
|||
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.',
|
||||
namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',
|
||||
weknoraTemplateTitle: 'WeKnora standard template',
|
||||
weknoraDockerImage: 'WeKnora standard image',
|
||||
weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',
|
||||
localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',
|
||||
weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',
|
||||
weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',
|
||||
recommendedTag: 'Recommended',
|
||||
templateNotConfigured: 'Template not configured',
|
||||
cardTemplateConfigured: 'Шаблон настроен',
|
||||
cardCredentialMissing: 'Нет API-ключа',
|
||||
cardTimeout: 'Таймаут {sec} с',
|
||||
cardTtl: 'Время жизни песочницы {sec} с',
|
||||
cardVolumeMounted: 'Том подключён',
|
||||
cardEnvVars: 'Переменных окружения: {count}',
|
||||
cardPrivateEndpoints: 'Разрешён доступ к частной сети',
|
||||
imageNotConfigured: 'Image not configured',
|
||||
localRuntimeSummary: 'WeKnora server process',
|
||||
templateApplied: 'Applied',
|
||||
refreshTemplates: 'Refresh templates',
|
||||
templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',
|
||||
templateSelectPlaceholder: 'Connect to the cluster to load templates',
|
||||
templateLoadHint: 'Enter the cluster connection and refresh. WeKnora creates its standard template when missing.',
|
||||
templateLoadFailed: 'Failed to load templates',
|
||||
standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',
|
||||
templateNotReady: 'The selected template is not ready. Refresh and wait for the build to finish.',
|
||||
connectionPassed: 'Connection verified. Templates below are loaded from this cluster.',
|
||||
connectionPassedTitle: 'Cluster connected',
|
||||
templateStepHint: 'WeKnora automatically creates its standard template when missing. You can continue after a template is ready.',
|
||||
loadingTemplates: 'Loading templates from the cluster...',
|
||||
templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',
|
||||
templateUntaggedHint: 'Сборки завершены, но ни одна не имеет тега default, поэтому при создании песочницы шаблон не находится. Удалите его в E2B и обновите список — WeKnora пересоберёт шаблон.',
|
||||
noTemplates: 'No templates were returned by this cluster.',
|
||||
templateReadyHint: 'Template “{name}” is ready and selected.',
|
||||
templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',
|
||||
templateStatuses: {
|
||||
ready: 'Ready',
|
||||
building: 'Building',
|
||||
untagged: 'Нет тега default',
|
||||
failed: 'Failed',
|
||||
unknown: 'Unknown',
|
||||
},
|
||||
allowPrivateEndpoints: 'Allow private cluster endpoints',
|
||||
allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',
|
||||
howToBuildTemplate: 'Sandbox cluster setup and template guide',
|
||||
noEnvVars: 'No additional environment variables. Add only values required by skills.',
|
||||
fieldRequired: 'Required',
|
||||
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
|
||||
cubeApiKeyWhere: 'Как включить аутентификацию в собственном кластере',
|
||||
e2bApiKeyHelp: 'Создайте ключ на странице API Keys в консоли E2B; обычно он начинается с e2b_.',
|
||||
e2bApiKeyWhere: 'Получить API-ключ в консоли E2B',
|
||||
apiKeyPlaceholder: 'Вставьте API-ключ',
|
||||
secretConfigured: 'Ключ настроен (повторно не показывается); введите новое значение для ротации',
|
||||
secretKeepHint: 'Настроено — оставьте пустым, чтобы не менять',
|
||||
e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
|
||||
e2bDomainOptional: 'Optional — the SDK default is used when empty',
|
||||
backends: {
|
||||
|
|
@ -4721,9 +4795,12 @@ export default {
|
|||
apiKey: 'API key',
|
||||
templateId: 'Template ID',
|
||||
httpTimeout: 'HTTP timeout (s)',
|
||||
httpTimeoutHelp: 'Сколько ждать ответа от управляющего API бэкенда, прежде чем считать эндпоинт недоступным. Пусто — 30 секунд.',
|
||||
sandboxTtl: 'Sandbox TTL (s)',
|
||||
sandboxTtlHelp: 'Сколько простаивающая песочница живёт до освобождения провайдером. Слишком мало — при продолжении сессии её придётся создавать заново, слишком много — простаивающие экземпляры продолжают тарифицироваться. Пусто — значение бэкенда по умолчанию.',
|
||||
dockerImage: 'Docker image',
|
||||
defaultTimeout: 'Execution timeout (s)',
|
||||
defaultTimeoutHelp: 'Максимальное время одного запуска скрипта навыка; по истечении он прерывается. Пусто — 60 секунд.',
|
||||
envVars: 'Environment variables',
|
||||
envKey: 'Name',
|
||||
envValue: 'Value',
|
||||
|
|
@ -4735,11 +4812,24 @@ export default {
|
|||
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?',
|
||||
recheck: 'Проверить снова',
|
||||
deepCheckIntro: 'Перед сохранением можно выполнить полную проверку: она создаёт временную песочницу, запускает скрипт, проверяет исходящую сеть и удаляет её.',
|
||||
deepCheckConfirm: 'Full verification runs a throwaway script. Remote backends also create and destroy a real sandbox and may consume a small amount of sandbox time. Continue?',
|
||||
checkPassed: 'All checks passed',
|
||||
checkFailed: 'Some checks failed',
|
||||
checkScopeConnection: 'Проверена только плоскость управления: эндпоинт отвечает, ключ действителен. Запустится ли скрипт на самом деле — пока не проверено.',
|
||||
checkScopeFull: 'Эндпоинт, ключ, шаблон, выполнение внутри песочницы и исходящая сеть проверены по-настоящему.',
|
||||
checkPendingHint: '{names} можно подтвердить только полной проверкой: она создаёт временную песочницу, запускает один скрипт и удаляет её.',
|
||||
skipReasons: {
|
||||
needs_deep_check: 'Нужна полная проверка',
|
||||
control_plane_unreachable: 'Пропущено: плоскость управления недоступна',
|
||||
environment_unavailable: 'Пропущено: среда выполнения недоступна',
|
||||
sandbox_not_created: 'Пропущено: песочница не создана',
|
||||
sandbox_exec_failed: 'Пропущено: выполнение в песочнице не удалось',
|
||||
},
|
||||
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
|
||||
checks: {
|
||||
environment_available: 'Runtime availability',
|
||||
client_build: 'Client construction',
|
||||
api_url_reachable: 'Endpoint reachability',
|
||||
credential_valid: 'Credential validity',
|
||||
|
|
@ -5145,10 +5235,10 @@ export default {
|
|||
sandboxConfig: 'Sandbox backend',
|
||||
sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
|
||||
sandboxBackend: 'Sandbox backend',
|
||||
sandboxBackendDefault: 'Use deployment defaults',
|
||||
sandboxBackendDefault: 'Disable sandbox',
|
||||
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.',
|
||||
sandboxNoConfigs: 'This workspace has no sandbox backend yet, so skill scripts will not run. 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?',
|
||||
|
|
|
|||
|
|
@ -4655,18 +4655,34 @@ export default {
|
|||
storageEngine: '存储引擎',
|
||||
sandbox: {
|
||||
title: '沙箱后端',
|
||||
description: '配置多份沙箱后端,智能体可各自选用其中一份。未填写的项沿用 .env 中的全局默认值。',
|
||||
description: '管理智能体技能使用的沙箱运行环境,每个智能体可以选择一份空间后端配置。',
|
||||
editorDescription: '配置空间运行环境,Docker、本地进程、CubeSandbox 和 E2B 使用同一套管理流程。',
|
||||
stepConnection: '连接',
|
||||
stepTemplate: '模板',
|
||||
stepRuntime: '运行配置',
|
||||
setupProgress: '沙箱配置进度',
|
||||
stepDescriptions: {
|
||||
connection: '先配置后端并验证连接,通过后再从集群加载模板。',
|
||||
template: '选择当前集群返回且已经就绪的运行模板。',
|
||||
runtime: '配置执行参数和环境变量,然后保存。',
|
||||
},
|
||||
back: '上一步',
|
||||
connectAndContinue: '连接并继续',
|
||||
loading: '加载沙箱配置...',
|
||||
loadFailed: '加载沙箱配置失败',
|
||||
backend: '沙箱后端',
|
||||
backendHint: '留空表示沿用全局默认',
|
||||
backendType: '沙箱类型',
|
||||
backendTypePlaceholder: '选择沙箱类型',
|
||||
scriptPolicyLabel: '允许在沙箱中执行技能脚本',
|
||||
scriptPolicyDesc: '关闭后本空间所有智能体只能阅读技能内容,不再执行脚本;已在运行的远端沙箱需结束会话后才释放。',
|
||||
backendDescriptions: {
|
||||
cube: '适合私有化或内网部署的自建 MicroVM 集群',
|
||||
e2b: 'E2B 托管服务或兼容 E2B 的集群',
|
||||
docker: '每次在当前 WeKnora 主机启动一个短生命周期容器执行脚本',
|
||||
local: '直接在 WeKnora 服务进程所在环境执行脚本',
|
||||
},
|
||||
addConfig: '添加沙箱后端',
|
||||
viewDeployDefaults: '查看部署默认配置',
|
||||
deployDefaultsTitle: '部署默认配置',
|
||||
deployDefaultsHint: '来自 .env 的全局配置。配置里留空的项即沿用这里的值。',
|
||||
deployDefaultBackend: '默认后端',
|
||||
apiKeyConfigured: '已配置',
|
||||
apiKeyNotConfigured: '未配置',
|
||||
viewClusterGuide: '集群搭建指南',
|
||||
configName: '配置名称',
|
||||
configNamePlaceholder: '如:生产 E2B',
|
||||
configNameRequired: '请填写配置名称',
|
||||
|
|
@ -4674,10 +4690,17 @@ export default {
|
|||
configDescriptionPlaceholder: '选填,用于区分多份同类型配置',
|
||||
createTitle: '添加沙箱后端',
|
||||
editTitle: '编辑沙箱后端',
|
||||
noConfigs: '还没有沙箱后端配置。智能体将使用部署默认配置运行技能脚本。',
|
||||
sectionBasic: '基本信息',
|
||||
sectionConnection: '集群连接',
|
||||
sectionRuntimeEnvironment: '运行环境',
|
||||
sectionTemplate: '运行模板',
|
||||
sectionRuntime: '执行设置',
|
||||
sectionEnvironment: '环境变量',
|
||||
noConfigs: '还没有沙箱后端配置。智能体未选择空间配置时不会执行技能脚本。',
|
||||
identityFieldHint: '该配置下有沙箱运行时,以下项无法修改:后端类型、API 端点、API Key、沙箱域名、Proxy 端点。',
|
||||
viewSandboxes: '查看沙箱占用',
|
||||
inventoryTitle: '沙箱占用',
|
||||
inventoryDrawerDesc: '该配置当前占用的沙箱,以及受影响的会话与智能体。',
|
||||
inventoryFailed: '获取沙箱占用失败',
|
||||
sandboxCount: '沙箱数量',
|
||||
sandboxCountUnknown: '未知(无法连接该后端)',
|
||||
|
|
@ -4703,9 +4726,60 @@ export default {
|
|||
scriptsEnabled: '已恢复本空间沙盒执行',
|
||||
policySaveFailed: '更新沙盒执行策略失败',
|
||||
legacyConfig: '已废弃',
|
||||
namedBackendHint: '具名配置支持 CubeSandbox 与 E2B。',
|
||||
namedBackendHint: '空间配置是唯一运行时来源;智能体没有选择配置时不会执行技能脚本。',
|
||||
weknoraTemplateTitle: 'WeKnora 标准模板',
|
||||
weknoraDockerImage: 'WeKnora 标准镜像',
|
||||
weknoraDockerImageHint: '每次执行都会基于该镜像创建一个隔离的短生命周期容器,不保留会话沙箱。',
|
||||
localRuntimeWarning: '本地进程会直接在 WeKnora 服务器上执行技能脚本,不具备容器或 MicroVM 隔离。仅建议在可信的开发空间使用。',
|
||||
weknoraTemplateOverview: 'WeKnora 负责提供标准运行环境。连接集群后会自动发现模板,缺少标准模板时自动创建。',
|
||||
weknoraTemplateDescription: '包含 WeKnora 技能所需的 Python、Node.js、CLI 工具、工作目录和非 root 执行用户。',
|
||||
recommendedTag: '推荐',
|
||||
templateNotConfigured: '未配置模板',
|
||||
cardTemplateConfigured: '模板已配置',
|
||||
cardCredentialMissing: '缺少 API Key',
|
||||
cardTimeout: '超时 {sec}s',
|
||||
cardTtl: '沙箱存活 {sec}s',
|
||||
cardVolumeMounted: '已挂载卷',
|
||||
cardEnvVars: '{count} 个环境变量',
|
||||
cardPrivateEndpoints: '允许访问私网',
|
||||
imageNotConfigured: '未配置镜像',
|
||||
localRuntimeSummary: 'WeKnora 服务器本地进程',
|
||||
templateApplied: '已使用',
|
||||
refreshTemplates: '刷新模板',
|
||||
templateSelectHelp: '模板由当前集群实时返回,保存时仅记录模板 ID,无需手工复制。',
|
||||
templateSelectPlaceholder: '先连接集群并加载模板',
|
||||
templateLoadHint: '填写集群连接后刷新模板;若缺少 WeKnora 标准模板,系统会自动创建。',
|
||||
templateLoadFailed: '模板列表加载失败',
|
||||
standardTemplateProvisioning: '已开始在集群中创建 WeKnora 标准模板,请稍后刷新查看状态',
|
||||
templateNotReady: '所选模板尚未构建完成,请刷新并等待状态就绪',
|
||||
connectionPassed: '连接验证通过,以下模板均从当前集群实时加载。',
|
||||
connectionPassedTitle: '集群连接成功',
|
||||
templateStepHint: '集群缺少标准模板时,WeKnora 会自动创建;模板就绪后才能继续。',
|
||||
loadingTemplates: '正在从集群加载模板…',
|
||||
templateBuildingHint: '标准模板正在自动构建,列表会自动刷新。',
|
||||
templateUntaggedHint: '构建已完成,但没有构建带 default 标签,创建沙箱时无法解析。请在 E2B 删除该模板,刷新后 WeKnora 会重新构建。',
|
||||
noTemplates: '当前集群未返回可用模板。',
|
||||
templateReadyHint: '模板「{name}」已就绪并选中。',
|
||||
templateProvisioningHint: '模板仍在构建中,状态会自动刷新。',
|
||||
templateStatuses: {
|
||||
ready: '已就绪',
|
||||
building: '构建中',
|
||||
untagged: '缺少 default 标签',
|
||||
failed: '失败',
|
||||
unknown: '未知',
|
||||
},
|
||||
allowPrivateEndpoints: '允许访问私网集群地址',
|
||||
allowPrivateEndpointsHint: '仅用于自建 Cube 等私网控制面;云元数据等链路本地地址始终禁止访问。',
|
||||
howToBuildTemplate: '沙箱集群搭建与模板说明',
|
||||
noEnvVars: '暂无额外环境变量,仅添加技能确实需要的值。',
|
||||
fieldRequired: '必填',
|
||||
cubeApiKeyOptional: '可留空 —— 自建 CubeSandbox 通常无鉴权',
|
||||
cubeApiKeyWhere: '自建集群如何开启鉴权',
|
||||
e2bApiKeyHelp: '在 E2B 控制台的 API Keys 页面创建,通常以 e2b_ 开头。',
|
||||
e2bApiKeyWhere: '前往 E2B 控制台获取 API Key',
|
||||
apiKeyPlaceholder: '粘贴 API Key',
|
||||
secretConfigured: '已配置密钥(不可回看);输入新值可轮换',
|
||||
secretKeepHint: '已配置,留空表示不修改',
|
||||
e2bApiUrlOptional: '可留空 —— 留空时使用 SDK 默认值',
|
||||
e2bDomainOptional: '可留空 —— 留空时使用 SDK 默认值',
|
||||
backends: {
|
||||
|
|
@ -4721,9 +4795,12 @@ export default {
|
|||
apiKey: 'API Key',
|
||||
templateId: '模板 ID',
|
||||
httpTimeout: 'HTTP 超时(秒)',
|
||||
httpTimeoutHelp: '调用沙箱后端管理接口的等待上限,超过即视为端点不可用。留空按 30 秒。',
|
||||
sandboxTtl: '沙箱 TTL(秒)',
|
||||
sandboxTtlHelp: '沙箱空闲多久后被远端回收。设得太短,会话继续时要重建沙箱;设得太长,闲置实例会一直计费。留空按后端默认值。',
|
||||
dockerImage: 'Docker 镜像',
|
||||
defaultTimeout: '执行超时(秒)',
|
||||
defaultTimeoutHelp: '单次技能脚本允许运行的最长时间,超时会被强制终止。留空按 60 秒。',
|
||||
envVars: '环境变量',
|
||||
envKey: '变量名',
|
||||
envValue: '变量值',
|
||||
|
|
@ -4735,11 +4812,24 @@ export default {
|
|||
saveFailed: '保存失败',
|
||||
testConnection: '测试连接',
|
||||
deepCheck: '完整验证',
|
||||
deepCheckConfirm: '完整验证会真实创建并销毁一个沙箱,消耗少量沙箱时长,是否继续?',
|
||||
recheck: '重新验证',
|
||||
deepCheckIntro: '保存前可以跑一次「完整验证」:真实创建一个临时沙箱、执行一次脚本并检查出网,随后自动销毁。',
|
||||
deepCheckConfirm: '完整验证会执行一次临时脚本;远端后端还会真实创建并销毁一个沙箱,可能消耗少量沙箱时长。是否继续?',
|
||||
checkPassed: '检测通过',
|
||||
checkFailed: '检测未通过',
|
||||
checkScopeConnection: '本次只验证了控制面:端点可达且凭据有效。是否真的能跑起脚本还没有验证。',
|
||||
checkScopeFull: '端点、凭据、模板、沙箱内执行与出网均已真实验证。',
|
||||
checkPendingHint: '{names} 需要「完整验证」才能确认:会真实创建一个临时沙箱、执行一次脚本再销毁。',
|
||||
noVolumeSupport: '该后端不支持挂载卷,依赖共享卷的技能将不可用。',
|
||||
skipReasons: {
|
||||
needs_deep_check: '需完整验证',
|
||||
control_plane_unreachable: '控制面不可达,已跳过',
|
||||
environment_unavailable: '运行环境不可用,已跳过',
|
||||
sandbox_not_created: '沙箱未创建,已跳过',
|
||||
sandbox_exec_failed: '沙箱内执行失败,已跳过',
|
||||
},
|
||||
checks: {
|
||||
environment_available: '运行环境可用性',
|
||||
client_build: '客户端构建',
|
||||
api_url_reachable: '端点可达性',
|
||||
credential_valid: '凭据有效性',
|
||||
|
|
@ -5145,10 +5235,10 @@ export default {
|
|||
sandboxConfig: '沙箱后端',
|
||||
sandboxConfigDesc: '选择该智能体的技能脚本在哪个沙箱后端中执行。',
|
||||
sandboxBackend: '沙箱后端',
|
||||
sandboxBackendDefault: '使用部署默认配置',
|
||||
sandboxBackendDefault: '不启用沙箱',
|
||||
sandboxBackendHint: '仅在启用技能执行时生效。所选配置被删除后,该智能体的技能执行会失败。',
|
||||
sandboxBackendMissing: '配置已删除',
|
||||
sandboxNoConfigs: '当前空间还没有具名沙箱后端配置,技能脚本将运行在部署默认配置上。可在「设置 - 沙箱后端」中添加。',
|
||||
sandboxNoConfigs: '当前空间还没有沙箱后端配置,技能脚本不会执行。可在「设置 - 沙箱后端」中添加。',
|
||||
sandboxInfoTitle: '为什么要选后端?',
|
||||
sandboxInfoContent: '不同后端对应不同的账号、区域与配额。同一会话的沙箱一旦创建,后续的附件、产物与销毁都会锁定在创建时那份配置上,改这里只影响之后新建的沙箱。',
|
||||
skillsInfoTitle: '什么是 Skills?',
|
||||
|
|
|
|||
|
|
@ -182,7 +182,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
|
|||
* 不进 prefetchChatInput:只有编辑智能体时才需要,而对话输入栏用不到,
|
||||
* 没必要让每次首屏都多打一次请求。
|
||||
*
|
||||
* 失败只吞掉不抛:这是可选资源——拿不到就只剩「使用部署默认配置」一项,
|
||||
* 失败只吞掉不抛:这是可选资源——拿不到就只剩「不启用沙箱」一项,
|
||||
* 智能体照样能编辑保存。调用方通常把它和一堆必需资源放在同一个
|
||||
* Promise.all 里,若在这里抛出,整个编辑器的依赖加载都会连坐
|
||||
* (技能可用性拿不到 ⇒ 技能配置分组直接消失)。
|
||||
|
|
|
|||
|
|
@ -1932,7 +1932,7 @@ 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;
|
||||
|
|
@ -2377,7 +2377,7 @@ const defaultFormData = {
|
|||
// Skills 设置
|
||||
skills_selection_mode: 'none' as 'all' | 'selected' | 'none',
|
||||
selected_skills: [] as string[],
|
||||
// 技能脚本运行在哪份沙箱后端配置上。留空表示使用部署默认配置。
|
||||
// 技能脚本运行在哪份空间沙箱配置上。留空表示禁用脚本执行。
|
||||
sandbox_config_id: '' as string,
|
||||
// 知识库设置:新建智能体默认选择 "全部知识库",
|
||||
// 让用户无需先去勾选 KB 即可上手;如有需要可改为 "selected" / "none"。
|
||||
|
|
|
|||
|
|
@ -362,6 +362,54 @@ graph TD
|
|||
>
|
||||
> It can span multiple paragraphs.
|
||||
|
||||
\`\`\`mermaid
|
||||
sequenceDiagram
|
||||
participant Driver as 驾驶员 (Driver)
|
||||
participant HMI as 人机交互界面 (HMI/Cluster)
|
||||
participant ADAS as 组合驾驶辅助系统 (ADAS ECU)
|
||||
participant Sensor as 传感器/定位模块
|
||||
participant Cloud as 云端服务平台 (可选)
|
||||
|
||||
Note over ADAS, Sensor: 阶段1:正常运行与监控
|
||||
Driver->>Sensor: 车辆正常行驶中
|
||||
Sensor->>ADAS: 状态数据 (环境、定位、车辆状态)
|
||||
ADAS-->>Driver: 维持组合驾驶辅助状态 (显示图标正常)
|
||||
|
||||
Note over ADAS, Sensor: 阶段2:触发接管条件
|
||||
alt 系统检测到需接管场景
|
||||
Sensor->>ADAS: 检测条件满足 (如: 地图数据缺失/限速变化/系统故障/驾驶员分心)
|
||||
ADAS->>HMI: 发送接管请求信号 (HOR Signal)
|
||||
|
||||
Note right of HMI: 阶段3:分级提醒策略 (符合国标要求)
|
||||
HMI-->>Driver: 视觉提示 (仪表盘图标闪烁/颜色变化)
|
||||
HMI-->>Driver: 听觉提示 (轻柔蜂鸣声)
|
||||
|
||||
ADAS->>HMI: 增强提醒 (若驾驶员无响应)
|
||||
HMI-->>Driver: 强视觉警告 (红色边框/文字)
|
||||
HMI-->>Driver: 强听觉警告 (连续急促蜂鸣)
|
||||
HMI-->>Driver: 触觉提示 (方向盘震动/座椅振动)
|
||||
end
|
||||
|
||||
Note over Driver, ADAS: 阶段4:驾驶员响应处理
|
||||
alt 驾驶员及时接管
|
||||
Driver->>HMI: 手握方向盘动作 (Torque/Grip Detection)
|
||||
HMI->>ADAS: 确认驾驶员介入信号
|
||||
ADAS-->>Driver: 退出自动驾驶,切换至人工驾驶模式
|
||||
ADAS->>HMI: 清除警告提示
|
||||
else 驾驶员未响应
|
||||
alt 达到最后接管时限 (e.g., T+5s)
|
||||
ADAS->>ADAS: 启动最小风险策略 (MRM/MLR)
|
||||
ADAS->>HMI: 触发紧急减速/停车提示
|
||||
HMI-->>Driver: 紧急警告 (最高级别)
|
||||
ADAS->>Sensor: 执行安全停车动作 (靠边、刹车、双闪)
|
||||
end
|
||||
end
|
||||
|
||||
Note over Cloud, Driver: 阶段5:数据记录与上报
|
||||
ADAS->>Cloud: 上传接管事件数据 (时间、原因、驾驶员响应)
|
||||
Note right of Cloud: 用于事故定责与算法优化
|
||||
\`\`\`
|
||||
|
||||
Done.`;
|
||||
|
||||
const streamBuffer = ref('');
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -21,7 +21,7 @@ const monoModules = import.meta.glob('@/assets/img/providers/mono/*/*.svg', {
|
|||
import: 'default',
|
||||
}) as Record<string, string>;
|
||||
|
||||
export type ProviderCategory = 'vectorstore' | 'storage' | 'websearch' | 'parser';
|
||||
export type ProviderCategory = 'vectorstore' | 'storage' | 'websearch' | 'parser' | 'sandbox';
|
||||
|
||||
export type LogoMatch = {
|
||||
mode: 'color' | 'mono';
|
||||
|
|
|
|||
|
|
@ -4,9 +4,6 @@ import (
|
|||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
"github.com/Tencent/WeKnora/internal/agent/approval"
|
||||
|
|
@ -352,10 +349,10 @@ func (s *agentService) resolveKBAndDocInfos(
|
|||
// 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
|
||||
// capability (remote MicroVMs expose 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.
|
||||
// process-wide singleton. Workspaces without a selected configuration resolve
|
||||
// to the disabled manager.
|
||||
func (s *agentService) initializeSkillsManager(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
|
|
@ -363,30 +360,18 @@ func (s *agentService) initializeSkillsManager(
|
|||
toolRegistry *tools.ToolRegistry,
|
||||
) (*skills.Manager, error) {
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
configID, err := sandboxConfigForExecution(ctx, s.sandboxPinner, sessionID, config.SandboxConfigID)
|
||||
sandboxMgr, configID, err := resolveSandboxForExecution(
|
||||
ctx, s.sandboxResolver, s.sandboxMgr, s.sandboxPinner,
|
||||
tenantID, sessionID, config.SandboxConfigID, s.sandboxPolicy,
|
||||
)
|
||||
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 := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
|
||||
if sandboxMode == "" {
|
||||
sandboxMode = "disabled"
|
||||
}
|
||||
sandboxTimeout := 60
|
||||
if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
sandboxTimeout = n
|
||||
}
|
||||
}
|
||||
logger.Infof(ctx, "Sandbox in use: mode=%s type=%s timeout=%ds",
|
||||
sandboxMode, sandboxMgr.GetType(), sandboxTimeout)
|
||||
logger.Infof(ctx, "Workspace sandbox in use: config=%s type=%s", configID, sandboxMgr.GetType())
|
||||
|
||||
// Create skills manager
|
||||
skillsConfig := &skills.ManagerConfig{
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
|
|
@ -147,17 +146,15 @@ func (s *sessionService) AgentQA(
|
|||
// 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.
|
||||
// filesystem capability so provider-neutral remote wiring stays here.
|
||||
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.
|
||||
// process-wide manager instead could inspect a different backend than the
|
||||
// named workspace config selected by this agent.
|
||||
inputStore, storeErr := stager.sessionSandboxInputStore(ctx, sessionID, agentConfig.SandboxConfigID)
|
||||
if storeErr != nil {
|
||||
return fmt.Errorf("resolve sandbox file store for session %s: %w", sessionID, storeErr)
|
||||
|
|
@ -537,15 +534,6 @@ func (s *sessionService) configureSkillsFromAgent(
|
|||
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" {
|
||||
agentConfig.SkillsEnabled = false
|
||||
agentConfig.SkillDirs = nil
|
||||
agentConfig.AllowedSkills = nil
|
||||
logger.Infof(ctx, "Sandbox is disabled: skills are not available")
|
||||
return
|
||||
}
|
||||
dir := getPreloadedSkillsDir()
|
||||
switch customAgent.Config.SkillsSelectionMode {
|
||||
case "all":
|
||||
|
|
|
|||
|
|
@ -59,9 +59,9 @@ type sessionAttachmentStager interface {
|
|||
// 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.
|
||||
// different workspace configs expose different capabilities. Remote backends
|
||||
// need attachment staging; stateless Docker/Local backends do not advertise a
|
||||
// session filesystem at all.
|
||||
func (s *agentService) sessionSandboxInputStore(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
|
|
@ -71,15 +71,12 @@ func (s *agentService) sessionSandboxInputStore(
|
|||
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,
|
||||
mgr, _, err := resolveSandboxForExecution(
|
||||
ctx, s.sandboxResolver, s.sandboxMgr, s.sandboxPinner,
|
||||
tenantID, sessionID, agentSandboxConfigID, s.sandboxPolicy,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)
|
||||
}
|
||||
return sessionSandboxFileStore(mgr), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -106,8 +106,6 @@ func (m *stagingSandboxManager) RemoveSessionInputPath(_ context.Context, _ stri
|
|||
}
|
||||
|
||||
func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {
|
||||
t.Setenv("WEKNORA_SANDBOX_MODE", "cube")
|
||||
|
||||
attachment := types.MessageAttachment{
|
||||
URL: "local://tenant/attachment-1",
|
||||
FileName: "report.pdf",
|
||||
|
|
@ -124,12 +122,16 @@ func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {
|
|||
fileService := &stagingFileService{
|
||||
files: map[string][]byte{attachment.URL: []byte("content")},
|
||||
}
|
||||
service := &agentService{sandboxMgr: manager, fileService: fileService}
|
||||
service := &agentService{
|
||||
sandboxMgr: manager, fileService: fileService,
|
||||
sandboxResolver: stubSandboxResolver{mgr: manager},
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
|
||||
|
||||
staged, err := service.stageSessionAttachments(
|
||||
context.Background(),
|
||||
ctx,
|
||||
"session-1",
|
||||
"",
|
||||
"cfg-remote",
|
||||
types.MessageAttachments{attachment, attachment},
|
||||
)
|
||||
|
||||
|
|
@ -142,14 +144,12 @@ func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {
|
|||
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})
|
||||
_, err = service.stageSessionAttachments(ctx, "session-1", "cfg-remote", 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).
|
||||
|
|
|
|||
|
|
@ -43,23 +43,6 @@ func (m *artifactFallbackManager) ReadSessionFile(ctx context.Context, sessionID
|
|||
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))
|
||||
|
||||
|
|
@ -68,38 +51,9 @@ func TestSandboxConfigForExistingSandboxReturnsEmptyWhenUnpinned(t *testing.T) {
|
|||
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".
|
||||
// Older sessions can still carry the historical default-config sentinel. The
|
||||
// fallback manager remains readable so those sessions can be cleaned up.
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -17,8 +17,6 @@ import (
|
|||
// 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{
|
||||
|
|
@ -43,8 +41,6 @@ func TestSessionSandboxInputStoreUsesNamedConfigNotDeploymentDefault(t *testing.
|
|||
// 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,
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import (
|
|||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
|
|
@ -86,7 +87,9 @@ func (p *SessionSandboxPinner) Pin(
|
|||
) (string, error) {
|
||||
configID = strings.TrimSpace(configID)
|
||||
if configID == "" {
|
||||
configID = types.SandboxConfigIDGlobalDefault
|
||||
// No workspace config means sandbox execution is disabled, so there is
|
||||
// no remote resource whose backend needs pinning.
|
||||
return "", nil
|
||||
}
|
||||
// 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
|
||||
|
|
@ -136,28 +139,58 @@ func (p *SessionSandboxPinner) Clear(ctx context.Context, sessionID string) erro
|
|||
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(
|
||||
// resolveSandboxForExecution resolves before pinning so stateless workspace
|
||||
// backends (docker/local) never leave a permanent session pin. Remote backends
|
||||
// pin before their first Create; concurrent callers adopt and re-resolve the
|
||||
// winning config before executing anything.
|
||||
func resolveSandboxForExecution(
|
||||
ctx context.Context,
|
||||
resolver sandbox.TenantSandboxResolver,
|
||||
fallback sandbox.Manager,
|
||||
pinner *SessionSandboxPinner,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
agentConfigID string,
|
||||
) (string, error) {
|
||||
policy WorkspaceSandboxPolicy,
|
||||
) (sandbox.Manager, string, error) {
|
||||
if pinner != nil && strings.TrimSpace(sessionID) != "" {
|
||||
pinned, err := pinner.Read(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if pinned != "" {
|
||||
mgr, err := resolveTenantSandboxForConfig(
|
||||
ctx, resolver, fallback, tenantID, pinned, policy,
|
||||
)
|
||||
return mgr, pinned, err
|
||||
}
|
||||
}
|
||||
|
||||
configID := strings.TrimSpace(agentConfigID)
|
||||
mgr, err := resolveTenantSandboxForConfig(
|
||||
ctx, resolver, fallback, tenantID, configID, policy,
|
||||
)
|
||||
if err != nil || mgr == nil {
|
||||
return mgr, configID, err
|
||||
}
|
||||
if mgr.GetType() != sandbox.SandboxTypeCube && mgr.GetType() != sandbox.SandboxTypeE2B {
|
||||
return mgr, configID, nil
|
||||
}
|
||||
if pinner == nil || strings.TrimSpace(sessionID) == "" {
|
||||
return agentConfigID, nil
|
||||
return mgr, configID, nil
|
||||
}
|
||||
pinned, err := pinner.Read(ctx, sessionID)
|
||||
|
||||
winner, err := pinner.Pin(ctx, sessionID, configID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, "", err
|
||||
}
|
||||
if pinned != "" {
|
||||
return pinned, nil
|
||||
if winner == configID {
|
||||
return mgr, winner, nil
|
||||
}
|
||||
return pinner.Pin(ctx, sessionID, agentConfigID)
|
||||
mgr, err = resolveTenantSandboxForConfig(
|
||||
ctx, resolver, fallback, tenantID, winner, policy,
|
||||
)
|
||||
return mgr, winner, err
|
||||
}
|
||||
|
||||
// sandboxConfigForExistingSandbox returns the config an already-created
|
||||
|
|
|
|||
|
|
@ -8,9 +8,21 @@ import (
|
|||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
type pinTestManager struct {
|
||||
typ sandbox.SandboxType
|
||||
}
|
||||
|
||||
func (m *pinTestManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *pinTestManager) Cleanup(context.Context) error { return nil }
|
||||
func (m *pinTestManager) GetSandbox() sandbox.Sandbox { return nil }
|
||||
func (m *pinTestManager) GetType() sandbox.SandboxType { return m.typ }
|
||||
|
||||
func newPinTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
|
||||
|
|
@ -52,13 +64,13 @@ func TestPinIsIdempotentAndReturnsExistingWinner(t *testing.T) {
|
|||
require.Equal(t, "cfg-a", second, "the first writer wins; later callers adopt it")
|
||||
}
|
||||
|
||||
func TestPinNormalizesEmptyConfigToSentinel(t *testing.T) {
|
||||
func TestPinLeavesEmptyConfigUnpinned(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)
|
||||
require.Empty(t, got)
|
||||
}
|
||||
|
||||
// A padded ID must land in the column exactly as Read will compare it, or the
|
||||
|
|
@ -134,3 +146,54 @@ func TestSoftDeleteHidesSandboxPin(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
require.Empty(t, read, "soft-deleted session must not expose its pin")
|
||||
}
|
||||
|
||||
func TestResolveSandboxForExecutionDoesNotPinStatelessBackend(t *testing.T) {
|
||||
pinner := NewSessionSandboxPinner(newPinTestDB(t))
|
||||
want := &pinTestManager{typ: sandbox.SandboxTypeLocal}
|
||||
|
||||
got, configID, err := resolveSandboxForExecution(
|
||||
context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,
|
||||
7, "s-1", "cfg-local", nil,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Same(t, want, got)
|
||||
require.Equal(t, "cfg-local", configID)
|
||||
pinned, err := pinner.Read(context.Background(), "s-1")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, pinned, "local and Docker executions must not leave a session binding")
|
||||
}
|
||||
|
||||
func TestResolveSandboxForExecutionPinsRemoteBackend(t *testing.T) {
|
||||
pinner := NewSessionSandboxPinner(newPinTestDB(t))
|
||||
want := &pinTestManager{typ: sandbox.SandboxTypeCube}
|
||||
|
||||
got, configID, err := resolveSandboxForExecution(
|
||||
context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,
|
||||
7, "s-1", "cfg-cube", nil,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Same(t, want, got)
|
||||
require.Equal(t, "cfg-cube", configID)
|
||||
pinned, err := pinner.Read(context.Background(), "s-1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "cfg-cube", pinned)
|
||||
}
|
||||
|
||||
func TestResolveSandboxForExecutionKeepsExistingRemotePin(t *testing.T) {
|
||||
pinner := NewSessionSandboxPinner(newPinTestDB(t))
|
||||
_, err := pinner.Pin(context.Background(), "s-1", "cfg-existing")
|
||||
require.NoError(t, err)
|
||||
want := &pinTestManager{typ: sandbox.SandboxTypeE2B}
|
||||
|
||||
got, configID, err := resolveSandboxForExecution(
|
||||
context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,
|
||||
7, "s-1", "cfg-new-agent-choice", nil,
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Same(t, want, got)
|
||||
require.Equal(t, "cfg-existing", configID,
|
||||
"re-pointing an agent must not move an existing remote session")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import (
|
|||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
|
@ -101,7 +102,7 @@ var ErrSandboxConfigNameRequired = stderrors.New("sandbox config name is require
|
|||
// 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",
|
||||
"named sandbox configs only support cube, e2b, docker and local backends",
|
||||
)
|
||||
|
||||
// SandboxInventory describes what a config holds and who a change disturbs.
|
||||
|
|
@ -131,6 +132,21 @@ type UpdateSandboxConfigInput struct {
|
|||
Config *types.TenantSandboxConfig
|
||||
}
|
||||
|
||||
// SandboxTemplateQueryInput describes an unsaved connection from the settings
|
||||
// drawer. ConfigID is optional and lets masked credentials resolve against the
|
||||
// stored row while editing.
|
||||
type SandboxTemplateQueryInput struct {
|
||||
Config *types.TenantSandboxConfig
|
||||
ConfigID string
|
||||
EnsureStandard bool
|
||||
}
|
||||
|
||||
type SandboxTemplateCatalog struct {
|
||||
Templates []sandbox.RemoteTemplate `json:"templates"`
|
||||
StandardTemplateID string `json:"standard_template_id,omitempty"`
|
||||
Provisioned bool `json:"provisioned"`
|
||||
}
|
||||
|
||||
// SandboxConfigAgentRepo is the slice of the agent repository this service
|
||||
// needs. Agent references are warnings, never grounds for refusing a change.
|
||||
type SandboxConfigAgentRepo interface {
|
||||
|
|
@ -181,7 +197,9 @@ func SanitizeSandboxConfig(
|
|||
}
|
||||
}
|
||||
for _, endpoint := range sandboxConfigEndpoints(merged) {
|
||||
if err := sandbox.ValidateOutboundURL(endpoint); err != nil {
|
||||
if err := sandbox.ValidateOutboundURLWithPolicy(endpoint, sandbox.OutboundURLPolicy{
|
||||
AllowPrivate: merged.AllowPrivateEndpoints,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
|
@ -241,8 +259,8 @@ func findWorkspacePolicyRow(
|
|||
return nil
|
||||
}
|
||||
|
||||
// WorkspaceScriptsDisabled reports whether agents that rely on the deployment
|
||||
// default (empty sandbox_config_id) must not execute skill scripts.
|
||||
// WorkspaceScriptsDisabled reports whether the workspace-wide kill switch is
|
||||
// active, regardless of which named backend an agent selected.
|
||||
func (s *TenantSandboxConfigService) WorkspaceScriptsDisabled(
|
||||
ctx context.Context, tenantID uint64,
|
||||
) (bool, error) {
|
||||
|
|
@ -253,8 +271,8 @@ func (s *TenantSandboxConfigService) WorkspaceScriptsDisabled(
|
|||
return findWorkspacePolicyRow(list) != nil, nil
|
||||
}
|
||||
|
||||
// SetWorkspaceScriptsDisabled toggles workspace-level script execution for
|
||||
// agents that do not point at a named cube/e2b config.
|
||||
// SetWorkspaceScriptsDisabled toggles script execution for the entire
|
||||
// workspace, across all named backend types.
|
||||
func (s *TenantSandboxConfigService) SetWorkspaceScriptsDisabled(
|
||||
ctx context.Context, tenantID uint64, disabled bool,
|
||||
) error {
|
||||
|
|
@ -339,6 +357,152 @@ func (s *TenantSandboxConfigService) Get(
|
|||
return entity, nil
|
||||
}
|
||||
|
||||
// QueryTemplates reads the provider's template catalog and optionally installs
|
||||
// the standard WeKnora image when it is absent. This is intentionally driven by
|
||||
// workspace credentials instead of deployment environment variables.
|
||||
func (s *TenantSandboxConfigService) QueryTemplates(
|
||||
ctx context.Context, tenantID uint64, in SandboxTemplateQueryInput,
|
||||
) (*SandboxTemplateCatalog, error) {
|
||||
var existing *types.TenantSandboxConfig
|
||||
if strings.TrimSpace(in.ConfigID) != "" {
|
||||
entity, err := s.repo.GetByID(ctx, tenantID, in.ConfigID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if entity == nil || types.IsSandboxWorkspacePolicyRow(entity) {
|
||||
return nil, apperrors.NewNotFoundError("sandbox config not found")
|
||||
}
|
||||
existing = entity.Config
|
||||
}
|
||||
merged := types.MergeSandboxConfigForUpdate(in.Config, existing)
|
||||
if merged == nil {
|
||||
merged = types.MergeSandboxConfigForUpdate(existing, nil)
|
||||
}
|
||||
if merged == nil {
|
||||
return nil, apperrors.NewBadRequestError("sandbox config is required")
|
||||
}
|
||||
|
||||
// Catalog access needs the control-plane connection but does not need a
|
||||
// spawn template yet. A private placeholder lets the same effective-config
|
||||
// validation protect every other required field without weakening runtime
|
||||
// validation.
|
||||
switch merged.SandboxType {
|
||||
case string(sandbox.SandboxTypeCube):
|
||||
if merged.Cube == nil {
|
||||
merged.Cube = &types.CubeSandboxConfig{}
|
||||
}
|
||||
if strings.TrimSpace(merged.Cube.TemplateID) == "" {
|
||||
merged.Cube.TemplateID = "__catalog__"
|
||||
}
|
||||
case string(sandbox.SandboxTypeE2B):
|
||||
if merged.E2B == nil {
|
||||
merged.E2B = &types.E2BSandboxConfig{}
|
||||
}
|
||||
if strings.TrimSpace(merged.E2B.TemplateID) == "" {
|
||||
merged.E2B.TemplateID = "__catalog__"
|
||||
}
|
||||
default:
|
||||
return nil, apperrors.NewBadRequestError(
|
||||
"sandbox template catalog only supports cube and e2b backends")
|
||||
}
|
||||
|
||||
for _, endpoint := range sandboxConfigEndpoints(merged) {
|
||||
if err := sandbox.ValidateOutboundURLWithPolicy(endpoint, sandbox.OutboundURLPolicy{
|
||||
AllowPrivate: merged.AllowPrivateEndpoints,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
effective, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DefaultConfig())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := s.newClient(effective)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
catalog, ok := any(client).(sandbox.RemoteTemplateCatalog)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("sandbox: provider %q does not expose templates", effective.Type)
|
||||
}
|
||||
templates, err := catalog.ListTemplates(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &SandboxTemplateCatalog{Templates: deduplicateSandboxTemplates(templates)}
|
||||
for _, item := range result.Templates {
|
||||
if item.Standard {
|
||||
result.StandardTemplateID = item.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
if in.EnsureStandard && result.StandardTemplateID == "" {
|
||||
standard, ensureErr := catalog.EnsureStandardTemplate(ctx)
|
||||
if ensureErr != nil {
|
||||
return nil, ensureErr
|
||||
}
|
||||
result.Provisioned = true
|
||||
result.StandardTemplateID = standard.ID
|
||||
result.Templates = deduplicateSandboxTemplates(append(result.Templates, *standard))
|
||||
}
|
||||
sort.SliceStable(result.Templates, func(i, j int) bool {
|
||||
if result.Templates[i].Standard != result.Templates[j].Standard {
|
||||
return result.Templates[i].Standard
|
||||
}
|
||||
return strings.ToLower(result.Templates[i].Name) < strings.ToLower(result.Templates[j].Name)
|
||||
})
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func deduplicateSandboxTemplates(items []sandbox.RemoteTemplate) []sandbox.RemoteTemplate {
|
||||
if len(items) < 2 {
|
||||
return items
|
||||
}
|
||||
result := make([]sandbox.RemoteTemplate, 0, len(items))
|
||||
indexByID := make(map[string]int, len(items))
|
||||
for _, item := range items {
|
||||
id := strings.TrimSpace(item.ID)
|
||||
if id == "" {
|
||||
result = append(result, item)
|
||||
continue
|
||||
}
|
||||
idx, exists := indexByID[id]
|
||||
if !exists {
|
||||
indexByID[id] = len(result)
|
||||
result = append(result, item)
|
||||
continue
|
||||
}
|
||||
current := &result[idx]
|
||||
current.Standard = current.Standard || item.Standard
|
||||
if templateStatusRank(item.Status) > templateStatusRank(current.Status) {
|
||||
current.Status = item.Status
|
||||
current.Version = item.Version
|
||||
current.UpdatedAt = item.UpdatedAt
|
||||
}
|
||||
if strings.TrimSpace(current.Name) == "" ||
|
||||
(strings.EqualFold(current.Name, sandbox.StandardTemplateName) && strings.Contains(item.Name, "/")) {
|
||||
current.Name = item.Name
|
||||
}
|
||||
if current.Image == "" {
|
||||
current.Image = item.Image
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func templateStatusRank(status string) int {
|
||||
switch strings.ToLower(strings.TrimSpace(status)) {
|
||||
case "ready", "available", "complete", "completed", "success", "succeeded":
|
||||
return 3
|
||||
case "building", "waiting", "pending", "queued", "processing":
|
||||
return 2
|
||||
case "failed", "error", "cancelled", "canceled":
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Inventory answers what changing or deleting this config would disturb.
|
||||
//
|
||||
// An unreachable provider is reported through Unverifiable rather than as an
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import (
|
|||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// testGlobalSandboxConfig mirrors a deployment's WEKNORA_SANDBOX_* values. Named
|
||||
// testGlobalSandboxConfig supplies built-in runtime tuning 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 {
|
||||
|
|
@ -108,6 +108,16 @@ func TestSandboxIdentityChanged(t *testing.T) {
|
|||
new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "private endpoint policy changes transport identity",
|
||||
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
|
||||
new: func() *types.TenantSandboxConfig {
|
||||
cfg := e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300)
|
||||
cfg.AllowPrivateEndpoints = true
|
||||
return cfg
|
||||
}(),
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
// Nothing is inherited, so filling in an endpoint that was blank
|
||||
// really does re-point the config at a different account.
|
||||
|
|
@ -269,12 +279,26 @@ func (s stubAgentRepo) ListNamesBySandboxConfigID(
|
|||
|
||||
type stubProviderClient struct {
|
||||
inventories [][]sandbox.RemoteSandboxSummary
|
||||
templates []sandbox.RemoteTemplate
|
||||
ensured *sandbox.RemoteTemplate
|
||||
|
||||
listCalls int
|
||||
deleted []string
|
||||
deleteCtxErr error
|
||||
}
|
||||
|
||||
func (s *stubProviderClient) ListTemplates(context.Context) ([]sandbox.RemoteTemplate, error) {
|
||||
return append([]sandbox.RemoteTemplate(nil), s.templates...), nil
|
||||
}
|
||||
|
||||
func (s *stubProviderClient) EnsureStandardTemplate(context.Context) (*sandbox.RemoteTemplate, error) {
|
||||
if s.ensured != nil {
|
||||
copy := *s.ensured
|
||||
return ©, nil
|
||||
}
|
||||
return &sandbox.RemoteTemplate{ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true}, nil
|
||||
}
|
||||
|
||||
func (s *stubProviderClient) List(
|
||||
ctx context.Context, _ sandbox.RemoteListFilter,
|
||||
) ([]sandbox.RemoteSandboxSummary, error) {
|
||||
|
|
@ -312,6 +336,62 @@ func newTestConfigService(
|
|||
return svc
|
||||
}
|
||||
|
||||
func TestQueryTemplatesEnsuresMissingWeKnoraTemplate(t *testing.T) {
|
||||
client := &stubProviderClient{
|
||||
templates: []sandbox.RemoteTemplate{{ID: "tpl-custom", Name: "custom", Status: "ready"}},
|
||||
ensured: &sandbox.RemoteTemplate{ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true},
|
||||
}
|
||||
svc := newTestConfigService(t, &fakeConfigRepo{}, client, stubAgentRepo{})
|
||||
|
||||
result, err := svc.QueryTemplates(context.Background(), 7, SandboxTemplateQueryInput{
|
||||
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "", 300),
|
||||
EnsureStandard: true,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.Provisioned)
|
||||
require.Equal(t, "tpl-weknora", result.StandardTemplateID)
|
||||
require.Len(t, result.Templates, 2)
|
||||
require.True(t, result.Templates[0].Standard, "standard template should sort first")
|
||||
}
|
||||
|
||||
func TestQueryTemplatesDeduplicatesSameProviderTemplateID(t *testing.T) {
|
||||
client := &stubProviderClient{templates: []sandbox.RemoteTemplate{
|
||||
{ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true},
|
||||
{ID: "tpl-weknora", Name: "project-b89e/weknora", Status: "ready", Standard: true},
|
||||
}}
|
||||
svc := newTestConfigService(t, &fakeConfigRepo{}, client, stubAgentRepo{})
|
||||
|
||||
result, err := svc.QueryTemplates(context.Background(), 7, SandboxTemplateQueryInput{
|
||||
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "", 300),
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Len(t, result.Templates, 1)
|
||||
require.Equal(t, "project-b89e/weknora", result.Templates[0].Name)
|
||||
require.Equal(t, "ready", result.Templates[0].Status)
|
||||
require.Equal(t, "tpl-weknora", result.StandardTemplateID)
|
||||
}
|
||||
|
||||
func TestQueryTemplatesResolvesMaskedStoredCredential(t *testing.T) {
|
||||
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
|
||||
ID: "cfg-a", TenantID: 7, SandboxType: "e2b",
|
||||
Config: e2bCfg("stored-secret", "https://api.e2b.app", "e2b.app", "old", 300),
|
||||
}}
|
||||
svc := NewTenantSandboxConfigService(repo, stubAgentRepo{}, sandbox.DefaultConfig())
|
||||
client := &stubProviderClient{templates: []sandbox.RemoteTemplate{{ID: "tpl-a", Name: "a", Status: "ready"}}}
|
||||
svc.newClient = func(cfg *sandbox.Config) (sandbox.ConfigSandboxClient, error) {
|
||||
require.Equal(t, "stored-secret", cfg.E2BAPIKey)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
_, err := svc.QueryTemplates(context.Background(), 7, SandboxTemplateQueryInput{
|
||||
ConfigID: "cfg-a",
|
||||
Config: e2bCfg(types.RedactedSecretPlaceholder, "https://api.e2b.app", "e2b.app", "", 300),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
|
|
@ -721,15 +801,37 @@ func TestSandboxesStillLiveErrorSupportsErrorsIs(t *testing.T) {
|
|||
require.True(t, stderrors.Is(err, ErrSandboxesStillLive))
|
||||
}
|
||||
|
||||
func TestCreateRejectsNonNamedSandboxBackend(t *testing.T) {
|
||||
svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})
|
||||
func TestCreateAcceptsStatelessNamedSandboxBackends(t *testing.T) {
|
||||
repo := &fakeConfigRepo{}
|
||||
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
|
||||
|
||||
_, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{
|
||||
local, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{
|
||||
Name: "local-dev",
|
||||
Config: &types.TenantSandboxConfig{SandboxType: "local"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "local", local.SandboxType)
|
||||
|
||||
require.ErrorIs(t, err, ErrNamedSandboxBackendUnsupported)
|
||||
docker, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{
|
||||
Name: "docker-dev",
|
||||
Config: &types.TenantSandboxConfig{
|
||||
SandboxType: "docker",
|
||||
Docker: &types.DockerSandboxConfig{Image: "weknora:test"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "docker", docker.SandboxType)
|
||||
}
|
||||
|
||||
func TestCreateRejectsDockerWithoutImage(t *testing.T) {
|
||||
svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})
|
||||
|
||||
_, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{
|
||||
Name: "docker-dev",
|
||||
Config: &types.TenantSandboxConfig{SandboxType: "docker"},
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, sandbox.ErrSandboxConfigIncomplete)
|
||||
}
|
||||
|
||||
func TestWorkspaceScriptsDisabledPolicy(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -7,8 +7,6 @@ package service
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
|
|
@ -58,16 +56,11 @@ func (l *tenantSandboxConfigLoader) Load(
|
|||
}
|
||||
|
||||
// WorkspaceSandboxPolicy reports whether sandbox execution is disabled for the
|
||||
// entire workspace, including agents bound to named cube/e2b configs.
|
||||
// entire workspace, including agents bound to any named backend config.
|
||||
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
|
||||
|
|
@ -77,17 +70,12 @@ func deploymentSandboxDisabled() bool {
|
|||
func resolveTenantSandboxForConfig(
|
||||
ctx context.Context,
|
||||
resolver sandbox.TenantSandboxResolver,
|
||||
fallback sandbox.Manager,
|
||||
_ 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.
|
||||
// ① Workspace kill switch — independent of resolver availability.
|
||||
if policy != nil && tenantID != 0 {
|
||||
disabled, err := policy.WorkspaceScriptsDisabled(ctx, tenantID)
|
||||
if err != nil {
|
||||
|
|
@ -99,12 +87,13 @@ func resolveTenantSandboxForConfig(
|
|||
}
|
||||
}
|
||||
|
||||
// ③ Default path: agents with no named config use the process-wide manager.
|
||||
// ② No named workspace config means sandbox execution is disabled. There is
|
||||
// no deployment-level provider fallback anymore.
|
||||
if configID == "" || configID == types.SandboxConfigIDGlobalDefault {
|
||||
return fallback, nil
|
||||
return sandbox.NewDisabledManager(), nil
|
||||
}
|
||||
|
||||
// ④ Named config: must not silently fall back to the deployment default.
|
||||
// ③ Named config: must not silently fall back to another backend.
|
||||
if tenantID == 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"sandbox: resolve config %q: missing workspace context", configID)
|
||||
|
|
|
|||
|
|
@ -181,10 +181,8 @@ 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.
|
||||
// Sandbox manager fallback is disabled; executable backends are resolved
|
||||
// from named workspace configurations.
|
||||
logger.Debugf(ctx, "[Container] Registering sandbox manager...")
|
||||
must(container.Provide(newSandboxManager))
|
||||
// Per-tenant sandbox backends: the resolver builds a manager per request
|
||||
|
|
@ -192,7 +190,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
|||
// 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...")
|
||||
|
|
|
|||
|
|
@ -1,9 +1,4 @@
|
|||
// 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 - workspace sandbox provider wiring.
|
||||
package container
|
||||
|
||||
import (
|
||||
|
|
@ -23,151 +18,20 @@ import (
|
|||
"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)
|
||||
// newSandboxManager is deliberately disabled. Every executable backend now
|
||||
// comes from a named workspace configuration resolved at request time.
|
||||
func newSandboxManager(
|
||||
redisClient *redis.Client,
|
||||
sessionRepo interfaces.SessionRepository,
|
||||
_ *redis.Client,
|
||||
_ 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
|
||||
return sandbox.NewDisabledManager()
|
||||
}
|
||||
|
||||
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"))
|
||||
}
|
||||
namespace := strings.TrimSpace(os.Getenv("WEKNORA_REDIS_NAMESPACE"))
|
||||
if namespace == "" {
|
||||
namespace = "weknora"
|
||||
}
|
||||
|
|
@ -178,21 +42,12 @@ func selectSessionBindingStore(
|
|||
}
|
||||
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",
|
||||
)
|
||||
}
|
||||
_ = requireRedis
|
||||
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
|
||||
|
|
@ -244,19 +99,15 @@ func (c *repositorySessionExistenceChecker) SessionExists(
|
|||
// buildGlobalSandboxConfig returns the process-wide *sandbox.Config that
|
||||
// per-tenant overrides are merged onto.
|
||||
func buildGlobalSandboxConfig() *sandbox.Config {
|
||||
return sandbox.DeploymentConfig()
|
||||
cfg := sandbox.DefaultConfig()
|
||||
cfg.Type = sandbox.SandboxTypeDisabled
|
||||
cfg.FallbackEnabled = false
|
||||
return cfg
|
||||
}
|
||||
|
||||
// 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.
|
||||
// newTenantSandboxResolver wires the workspace-config resolver. The
|
||||
// process-wide manager is disabled; agents without a selected config stay
|
||||
// disabled as well.
|
||||
func newTenantSandboxResolver(
|
||||
defaultManager sandbox.Manager,
|
||||
loader sandbox.TenantSandboxConfigLoader,
|
||||
|
|
@ -265,10 +116,9 @@ func newTenantSandboxResolver(
|
|||
) 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.
|
||||
// Tenants may configure any supported backend regardless of process startup
|
||||
// mode. Remote configs use this binding store for session persistence;
|
||||
// Docker and Local configs remain stateless.
|
||||
store, storeKind, err := selectSessionBindingStore(redisClient, true)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx,
|
||||
|
|
|
|||
|
|
@ -26,15 +26,7 @@ func TestSelectSessionBindingStorePrefersRedis(t *testing.T) {
|
|||
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")
|
||||
|
||||
func TestSelectSessionBindingStoreUsesMemoryWithoutRedis(t *testing.T) {
|
||||
store, kind, err := selectSessionBindingStore(nil, true)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "memory", kind)
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ import (
|
|||
stderrors "errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
|
@ -26,22 +28,39 @@ type SandboxCheckRequest struct {
|
|||
// 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 additionally runs a throwaway script. For remote backends this also
|
||||
// creates and destroys one sandbox, which is the only way to validate the
|
||||
// template ID, data plane, in-sandbox execution, and outbound egress. It may
|
||||
// consume 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"`
|
||||
Name string `json:"name"`
|
||||
OK *bool `json:"ok"`
|
||||
// Message carries free-form provider detail for an executed probe.
|
||||
Message string `json:"message,omitempty"`
|
||||
// Reason is a stable code explaining why a probe was skipped. It exists so
|
||||
// the UI can phrase the skip in the operator's language instead of echoing
|
||||
// a server-side sentence.
|
||||
Reason string `json:"reason,omitempty"`
|
||||
LatencyMS int64 `json:"latency_ms,omitempty"`
|
||||
}
|
||||
|
||||
// Why a probe was not executed. Kept as codes because the operator reads them
|
||||
// in the frontend, which is localized.
|
||||
const (
|
||||
// The probe needs a real sandbox, so it only runs on an opt-in deep check.
|
||||
skipReasonNeedsDeepCheck = "needs_deep_check"
|
||||
// An earlier probe failed and this one cannot be reached without it.
|
||||
skipReasonControlPlaneUnreachable = "control_plane_unreachable"
|
||||
skipReasonEnvironmentUnavailable = "environment_unavailable"
|
||||
skipReasonSandboxNotCreated = "sandbox_not_created"
|
||||
skipReasonSandboxExecFailed = "sandbox_exec_failed"
|
||||
)
|
||||
|
||||
// SandboxCheckResponse aggregates the probes for one sandbox configuration.
|
||||
type SandboxCheckResponse struct {
|
||||
OK bool `json:"ok"`
|
||||
|
|
@ -62,13 +81,13 @@ func (r *SandboxCheckResponse) add(name string, ok bool, message string, latency
|
|||
}
|
||||
|
||||
// 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})
|
||||
func (r *SandboxCheckResponse) skip(name, reason string) {
|
||||
r.Checks = append(r.Checks, SandboxCheckItem{Name: name, OK: nil, Reason: reason})
|
||||
}
|
||||
|
||||
// CheckSandboxConfig tests a sandbox configuration without persisting it.
|
||||
// @Summary 测试沙箱连通性
|
||||
// @Description 使用当前填写的参数测试沙箱后端连通性,不保存配置;deep=true 会额外创建并销毁一个沙箱
|
||||
// @Description 使用当前填写的参数测试沙箱后端,不保存配置;deep=true 会执行临时脚本,远端后端还会创建并销毁一个沙箱
|
||||
// @Tags 系统
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
|
|
@ -110,18 +129,26 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {
|
|||
incoming = stored
|
||||
}
|
||||
}
|
||||
if !req.Deep {
|
||||
incoming = sandboxConnectionCheckConfig(incoming)
|
||||
}
|
||||
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())
|
||||
effective, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DefaultConfig())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
result := &SandboxCheckResponse{OK: true, Provider: string(effective.Type)}
|
||||
if effective.Type == sandbox.SandboxTypeDocker || effective.Type == sandbox.SandboxTypeLocal {
|
||||
h.runStatelessSandboxCheck(ctx, effective, req.Deep, result)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
|
||||
return
|
||||
}
|
||||
|
||||
client, err := sandbox.NewRemoteClientForCheck(effective)
|
||||
if err != nil {
|
||||
|
|
@ -137,7 +164,7 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {
|
|||
latency := time.Since(start).Milliseconds()
|
||||
if healthErr != nil {
|
||||
result.add("api_url_reachable", false, sandboxCheckReason(healthErr), latency)
|
||||
result.skip("credential_valid", "未检测(控制面不可达)")
|
||||
result.skip("credential_valid", skipReasonControlPlaneUnreachable)
|
||||
} else {
|
||||
result.add("api_url_reachable", true, "", latency)
|
||||
result.add("credential_valid", true, "", 0)
|
||||
|
|
@ -151,9 +178,13 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {
|
|||
}
|
||||
|
||||
if !req.Deep || healthErr != nil {
|
||||
result.skip("template_exists", "未检测(需完整验证)")
|
||||
result.skip("sandbox_exec", "未检测(需完整验证)")
|
||||
result.skip("egress_available", "未检测(需完整验证)")
|
||||
reason := skipReasonNeedsDeepCheck
|
||||
if healthErr != nil {
|
||||
reason = skipReasonControlPlaneUnreachable
|
||||
}
|
||||
result.skip("template_exists", reason)
|
||||
result.skip("sandbox_exec", reason)
|
||||
result.skip("egress_available", reason)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
|
||||
return
|
||||
}
|
||||
|
|
@ -162,6 +193,183 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {
|
|||
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
|
||||
}
|
||||
|
||||
// sandboxConnectionCheckConfig supplies a private template placeholder for a
|
||||
// shallow remote probe. Connectivity is deliberately checked before template
|
||||
// discovery in the settings wizard, and Health never uses this value.
|
||||
func sandboxConnectionCheckConfig(cfg *types.TenantSandboxConfig) *types.TenantSandboxConfig {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
copy := *cfg
|
||||
switch sandbox.SandboxType(copy.SandboxType) {
|
||||
case sandbox.SandboxTypeCube:
|
||||
cube := types.CubeSandboxConfig{}
|
||||
if copy.Cube != nil {
|
||||
cube = *copy.Cube
|
||||
}
|
||||
if strings.TrimSpace(cube.TemplateID) == "" {
|
||||
cube.TemplateID = "__connection_check__"
|
||||
}
|
||||
copy.Cube = &cube
|
||||
case sandbox.SandboxTypeE2B:
|
||||
e2b := types.E2BSandboxConfig{}
|
||||
if copy.E2B != nil {
|
||||
e2b = *copy.E2B
|
||||
}
|
||||
if strings.TrimSpace(e2b.TemplateID) == "" {
|
||||
e2b.TemplateID = "__connection_check__"
|
||||
}
|
||||
copy.E2B = &e2b
|
||||
}
|
||||
return ©
|
||||
}
|
||||
|
||||
func (h *SystemHandler) runStatelessSandboxCheck(
|
||||
ctx context.Context,
|
||||
cfg *sandbox.Config,
|
||||
deep bool,
|
||||
result *SandboxCheckResponse,
|
||||
) {
|
||||
cfg.FallbackEnabled = false
|
||||
mgr, err := sandbox.NewManager(cfg)
|
||||
if err != nil {
|
||||
result.add("environment_available", false, err.Error(), 0)
|
||||
result.skip("sandbox_exec", skipReasonEnvironmentUnavailable)
|
||||
return
|
||||
}
|
||||
defer func() { _ = mgr.Cleanup(context.WithoutCancel(ctx)) }()
|
||||
active := mgr.GetSandbox()
|
||||
available := active != nil && active.IsAvailable(ctx)
|
||||
result.add("environment_available", available, "", 0)
|
||||
if !available || !deep {
|
||||
reason := skipReasonNeedsDeepCheck
|
||||
if !available {
|
||||
reason = skipReasonEnvironmentUnavailable
|
||||
}
|
||||
result.skip("sandbox_exec", reason)
|
||||
return
|
||||
}
|
||||
|
||||
dir, err := createProbeStagingDir()
|
||||
if err != nil {
|
||||
result.add("sandbox_exec", false, err.Error(), 0)
|
||||
return
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(dir) }()
|
||||
// Docker executes as a non-root user that differs from the WeKnora process
|
||||
// owner. The isolated bind-mount directory and probe must be traversable and
|
||||
// readable by that user.
|
||||
if err := os.Chmod(dir, 0o755); err != nil {
|
||||
result.add("sandbox_exec", false, err.Error(), 0)
|
||||
return
|
||||
}
|
||||
path := filepath.Join(dir, "check.sh")
|
||||
const script = "#!/bin/sh\nprintf 'weknora-ok\\n'\n"
|
||||
if err := os.WriteFile(path, []byte(script), 0o644); err != nil {
|
||||
result.add("sandbox_exec", false, err.Error(), 0)
|
||||
return
|
||||
}
|
||||
if err := os.Chmod(path, 0o644); err != nil {
|
||||
result.add("sandbox_exec", false, err.Error(), 0)
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
execResult, err := mgr.Execute(ctx, &sandbox.ExecuteConfig{
|
||||
Script: path,
|
||||
ScriptContent: script,
|
||||
Timeout: 90 * time.Second,
|
||||
})
|
||||
latency := time.Since(start).Milliseconds()
|
||||
if err != nil {
|
||||
result.add("sandbox_exec", false, err.Error(), latency)
|
||||
return
|
||||
}
|
||||
if execResult == nil || !strings.Contains(execResult.Stdout, "weknora-ok") {
|
||||
if execResult == nil {
|
||||
result.add("sandbox_exec", false, "沙箱没有返回执行结果", latency)
|
||||
return
|
||||
}
|
||||
message := describeProbeMismatch(
|
||||
execResult.ExitCode, execResult.Killed,
|
||||
execResult.Stdout, execResult.Stderr, execResult.Error,
|
||||
)
|
||||
if cfg.Type == sandbox.SandboxTypeDocker && probeScriptWasInvisible(execResult.Stderr) {
|
||||
message += ";容器没有看到挂载进去的脚本,请确认 Docker 运行时共享了目录 " + dir +
|
||||
"(Docker Desktop / colima 需要在文件共享设置里包含该路径)"
|
||||
}
|
||||
result.add("sandbox_exec", false, message, latency)
|
||||
return
|
||||
}
|
||||
result.add("sandbox_exec", true, "", latency)
|
||||
}
|
||||
|
||||
// createProbeStagingDir makes the directory the probe script is bind-mounted
|
||||
// from. The OS temp dir looks like the obvious home for it but is the wrong
|
||||
// choice for Docker: on macOS runtimes $TMPDIR lives under /var/folders, which
|
||||
// the Docker VM does not share, so the mount arrives empty and the probe fails
|
||||
// where real skill runs — staged under the process working directory, next to
|
||||
// skills/ — succeed. Stage where the real scripts live and fall back to the temp
|
||||
// dir only when the working directory is not writable.
|
||||
func createProbeStagingDir() (string, error) {
|
||||
if wd, err := os.Getwd(); err == nil {
|
||||
if dir, err := os.MkdirTemp(wd, ".weknora-sandbox-check-*"); err == nil {
|
||||
return dir, nil
|
||||
}
|
||||
}
|
||||
return os.MkdirTemp("", "weknora-sandbox-check-*")
|
||||
}
|
||||
|
||||
// probeScriptWasInvisible reports whether the interpreter could not find the
|
||||
// script at all, which for Docker means the bind mount never carried it into
|
||||
// the container rather than anything being wrong with the image.
|
||||
func probeScriptWasInvisible(stderr string) bool {
|
||||
lowered := strings.ToLower(stderr)
|
||||
return strings.Contains(lowered, "check.sh") &&
|
||||
(strings.Contains(lowered, "no such file") ||
|
||||
strings.Contains(lowered, "not found") ||
|
||||
strings.Contains(lowered, "cannot open"))
|
||||
}
|
||||
|
||||
// describeProbeMismatch reports why the probe script did not print its marker.
|
||||
// "命令输出与预期不符" on its own hides the exit code and the stderr line that
|
||||
// normally name the actual problem — a missing interpreter, an image entrypoint
|
||||
// that swallowed the command, or a bind mount that never reached the Docker VM.
|
||||
func describeProbeMismatch(exitCode int, killed bool, stdout, stderr, execErr string) string {
|
||||
parts := []string{fmt.Sprintf("退出码 %d", exitCode)}
|
||||
if killed {
|
||||
parts = append(parts, "执行超时被终止")
|
||||
}
|
||||
switch {
|
||||
case firstProbeLine(stderr) != "":
|
||||
parts = append(parts, "stderr: "+firstProbeLine(stderr))
|
||||
case firstProbeLine(stdout) != "":
|
||||
parts = append(parts, "stdout: "+firstProbeLine(stdout))
|
||||
default:
|
||||
parts = append(parts, "没有任何输出")
|
||||
}
|
||||
if trimmed := strings.TrimSpace(execErr); trimmed != "" {
|
||||
parts = append(parts, trimmed)
|
||||
}
|
||||
return strings.Join(parts, ";")
|
||||
}
|
||||
|
||||
// firstProbeLine picks the first non-empty line and caps it, so one runaway log
|
||||
// line cannot flood the check panel.
|
||||
func firstProbeLine(output string) string {
|
||||
for _, line := range strings.Split(output, "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
if len(trimmed) > 300 {
|
||||
return trimmed[:300] + "…"
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// 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(
|
||||
|
|
@ -182,9 +390,9 @@ func (h *SystemHandler) runDeepSandboxCheck(
|
|||
},
|
||||
})
|
||||
if err != nil {
|
||||
result.add("template_exists", false, sandboxCheckReason(err), 0)
|
||||
result.skip("sandbox_exec", "未检测(沙箱未创建)")
|
||||
result.skip("egress_available", "未检测(沙箱未创建)")
|
||||
result.add("template_exists", false, explainSandboxCreateFailure(ctx, client, cfg, err), 0)
|
||||
result.skip("sandbox_exec", skipReasonSandboxNotCreated)
|
||||
result.skip("egress_available", skipReasonSandboxNotCreated)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
|
|
@ -212,11 +420,18 @@ func (h *SystemHandler) runDeepSandboxCheck(
|
|||
switch {
|
||||
case err != nil:
|
||||
result.add("sandbox_exec", false, sandboxCheckReason(err), latency)
|
||||
result.skip("egress_available", "未检测(沙箱执行失败)")
|
||||
result.skip("egress_available", skipReasonSandboxExecFailed)
|
||||
return
|
||||
case execResult == nil || !strings.Contains(execResult.Stdout, marker):
|
||||
result.add("sandbox_exec", false, "命令输出与预期不符", latency)
|
||||
result.skip("egress_available", "未检测(沙箱执行失败)")
|
||||
case execResult == nil:
|
||||
result.add("sandbox_exec", false, "沙箱没有返回执行结果", latency)
|
||||
result.skip("egress_available", skipReasonSandboxExecFailed)
|
||||
return
|
||||
case !strings.Contains(execResult.Stdout, marker):
|
||||
result.add("sandbox_exec", false, describeProbeMismatch(
|
||||
execResult.ExitCode, execResult.Killed,
|
||||
execResult.Stdout, execResult.Stderr, "",
|
||||
), latency)
|
||||
result.skip("egress_available", skipReasonSandboxExecFailed)
|
||||
return
|
||||
default:
|
||||
result.add("sandbox_exec", true, "", latency)
|
||||
|
|
@ -288,6 +503,72 @@ func (h *SystemHandler) probeSandboxEgress(
|
|||
}
|
||||
}
|
||||
|
||||
// explainSandboxCreateFailure turns a failed sandbox creation into a cause the
|
||||
// operator can act on.
|
||||
//
|
||||
// A 404 from the provider is not proof that the template is gone: the E2B SDK
|
||||
// discards the response body of any 404 on the create endpoint and substitutes
|
||||
// a fixed "template not found" sentence, so the message alone cannot tell a
|
||||
// deleted template apart from one whose build cannot boot yet. The catalog is
|
||||
// the only place that distinction exists, so it is consulted before blaming the
|
||||
// template ID the admin just picked from a list.
|
||||
func explainSandboxCreateFailure(
|
||||
ctx context.Context,
|
||||
client sandbox.RemoteSandboxClient,
|
||||
cfg *sandbox.Config,
|
||||
err error,
|
||||
) string {
|
||||
reason := sandboxCheckReason(err)
|
||||
var remoteErr *sandbox.RemoteError
|
||||
if !stderrors.As(err, &remoteErr) {
|
||||
return reason
|
||||
}
|
||||
// A create-time 404 is classified as InvalidRequest, not NotFound, because
|
||||
// for the lifecycle it means "bad argument" rather than "sandbox is gone".
|
||||
// Diagnosis needs the status itself.
|
||||
if remoteErr.Kind != sandbox.RemoteErrorKindNotFound &&
|
||||
remoteErr.StatusCode != http.StatusNotFound {
|
||||
return reason
|
||||
}
|
||||
templateID := strings.TrimSpace(sandbox.EffectiveTemplateID(cfg))
|
||||
catalog, ok := client.(sandbox.RemoteTemplateCatalog)
|
||||
if !ok || templateID == "" {
|
||||
return reason
|
||||
}
|
||||
templates, listErr := catalog.ListTemplates(ctx)
|
||||
if listErr != nil {
|
||||
logger.Warnf(ctx, "[SandboxCheck] template lookup after create 404 failed: %v", listErr)
|
||||
return reason
|
||||
}
|
||||
for _, tpl := range templates {
|
||||
if tpl.ID != templateID && !strings.EqualFold(tpl.Name, templateID) {
|
||||
continue
|
||||
}
|
||||
if tpl.Status == sandbox.TemplateStatusUntagged {
|
||||
return fmt.Sprintf(
|
||||
"模板 %s 的构建已完成,但没有一个构建带上 %q 标签,创建沙箱时无法解析;"+
|
||||
"请重新构建该模板(删除后由 WeKnora 重新创建即可)",
|
||||
templateID, sandbox.DefaultE2BTemplateTag,
|
||||
)
|
||||
}
|
||||
if tpl.Status == "ready" || tpl.Status == "" {
|
||||
return fmt.Sprintf(
|
||||
"模板 %s 在列表中已就绪,但集群拒绝创建沙箱(HTTP 404);"+
|
||||
"通常是构建快照尚未生效,请稍后重试或重新构建模板",
|
||||
templateID,
|
||||
)
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
"模板 %s 存在,但构建状态为 %s,还不能启动沙箱;请等待构建完成或查看构建日志",
|
||||
templateID, tpl.Status,
|
||||
)
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
"当前 API Key 看不到模板 %s:模板可能已删除,或该 Key 属于其他团队/集群",
|
||||
templateID,
|
||||
)
|
||||
}
|
||||
|
||||
// shellSingleQuote wraps s for safe inclusion in a single-quoted shell string.
|
||||
func shellSingleQuote(s string) string {
|
||||
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestSandboxConnectionCheckConfigAllowsTemplateDiscoveryAfterConnection(t *testing.T) {
|
||||
incoming := &types.TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
E2B: &types.E2BSandboxConfig{APIKey: "key"},
|
||||
}
|
||||
|
||||
got := sandboxConnectionCheckConfig(incoming)
|
||||
|
||||
require.Equal(t, "__connection_check__", got.E2B.TemplateID)
|
||||
require.Empty(t, incoming.E2B.TemplateID, "the submitted form must not be mutated")
|
||||
}
|
||||
|
||||
func TestRunStatelessSandboxCheckLocal(t *testing.T) {
|
||||
cfg := sandbox.DefaultConfig()
|
||||
cfg.Type = sandbox.SandboxTypeLocal
|
||||
result := &SandboxCheckResponse{OK: true, Provider: string(cfg.Type)}
|
||||
|
||||
(&SystemHandler{}).runStatelessSandboxCheck(context.Background(), cfg, true, result)
|
||||
|
||||
require.True(t, result.OK)
|
||||
require.Len(t, result.Checks, 2)
|
||||
require.Equal(t, "environment_available", result.Checks[0].Name)
|
||||
require.NotNil(t, result.Checks[0].OK)
|
||||
require.True(t, *result.Checks[0].OK)
|
||||
require.Equal(t, "sandbox_exec", result.Checks[1].Name)
|
||||
require.NotNil(t, result.Checks[1].OK)
|
||||
require.True(t, *result.Checks[1].OK)
|
||||
}
|
||||
|
|
@ -24,18 +24,45 @@ type sandboxConfigService interface {
|
|||
Inventory(context.Context, uint64, string) (service.SandboxInventory, error)
|
||||
WorkspaceScriptsDisabled(context.Context, uint64) (bool, error)
|
||||
SetWorkspaceScriptsDisabled(context.Context, uint64, bool) error
|
||||
QueryTemplates(context.Context, uint64, service.SandboxTemplateQueryInput) (*service.SandboxTemplateCatalog, error)
|
||||
}
|
||||
|
||||
type sandboxTemplateQueryRequest struct {
|
||||
Config *types.TenantSandboxConfig `json:"config"`
|
||||
ConfigID string `json:"config_id,omitempty"`
|
||||
EnsureStandard bool `json:"ensure_standard"`
|
||||
}
|
||||
|
||||
// QueryTemplates returns the templates visible through an unsaved workspace
|
||||
// connection. When requested, it also starts provisioning the standard
|
||||
// WeKnora image if that cluster does not have one yet.
|
||||
func (h *SandboxConfigHandler) QueryTemplates(c *gin.Context) {
|
||||
var req sandboxTemplateQueryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
result, err := h.service.QueryTemplates(c.Request.Context(), sandboxConfigTenantID(c),
|
||||
service.SandboxTemplateQueryInput{
|
||||
Config: req.Config,
|
||||
ConfigID: req.ConfigID,
|
||||
EnsureStandard: req.EnsureStandard,
|
||||
})
|
||||
if err != nil {
|
||||
respondSandboxConfigServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
|
||||
}
|
||||
|
||||
type SandboxConfigHandler struct {
|
||||
service sandboxConfigService
|
||||
defaults *sandbox.ConfigDefaults
|
||||
service sandboxConfigService
|
||||
}
|
||||
|
||||
func NewSandboxConfigHandler(
|
||||
service *service.TenantSandboxConfigService,
|
||||
defaults *sandbox.ConfigDefaults,
|
||||
) *SandboxConfigHandler {
|
||||
return &SandboxConfigHandler{service: service, defaults: defaults}
|
||||
return &SandboxConfigHandler{service: service}
|
||||
}
|
||||
|
||||
type sandboxConfigRequest struct {
|
||||
|
|
@ -143,7 +170,7 @@ func respondSandboxConfigServiceError(c *gin.Context, err error) {
|
|||
|
||||
// List godoc
|
||||
// @Summary List sandbox configs
|
||||
// @Description List workspace sandbox backend configs with credentials masked and deployment defaults included.
|
||||
// @Description List workspace sandbox backend configs with credentials masked.
|
||||
// @Tags SandboxConfig
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "Sandbox configs and defaults"
|
||||
|
|
@ -171,7 +198,6 @@ func (h *SandboxConfigHandler) List(c *gin.Context) {
|
|||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": data,
|
||||
"defaults": h.defaults,
|
||||
"workspace_scripts_disabled": disabled,
|
||||
})
|
||||
}
|
||||
|
|
@ -180,7 +206,7 @@ type workspacePolicyRequest struct {
|
|||
ScriptsDisabled bool `json:"scripts_disabled"`
|
||||
}
|
||||
|
||||
// SetWorkspacePolicy toggles script execution for agents that use the deployment default.
|
||||
// SetWorkspacePolicy toggles script execution for the whole workspace.
|
||||
func (h *SandboxConfigHandler) SetWorkspacePolicy(c *gin.Context) {
|
||||
var req workspacePolicyRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
|
|
|
|||
|
|
@ -110,7 +110,7 @@ func TestSandboxConfigDeletePassesForceQuery(t *testing.T) {
|
|||
gin.SetMode(gin.TestMode)
|
||||
|
||||
svc := &fakeSandboxConfigService{}
|
||||
h := &SandboxConfigHandler{service: svc, defaults: &sandbox.ConfigDefaults{}}
|
||||
h := &SandboxConfigHandler{service: svc}
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set(types.TenantIDContextKey.String(), uint64(42))
|
||||
|
|
@ -247,3 +247,11 @@ func (s *fakeSandboxConfigService) SetWorkspaceScriptsDisabled(
|
|||
) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *fakeSandboxConfigService) QueryTemplates(
|
||||
context.Context,
|
||||
uint64,
|
||||
service.SandboxTemplateQueryInput,
|
||||
) (*service.SandboxTemplateCatalog, error) {
|
||||
return &service.SandboxTemplateCatalog{}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ package handler
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
|
|
@ -58,15 +57,11 @@ func (h *SkillHandler) ListSkills(c *gin.Context) {
|
|||
})
|
||||
}
|
||||
|
||||
// skills_available: true only when sandbox is enabled (docker or local), so frontend can hide/disable Skills UI
|
||||
sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")
|
||||
skillsAvailable := sandboxMode != "" && sandboxMode != "disabled"
|
||||
|
||||
logger.Infof(ctx, "skills_available: %v, sandboxMode: %s", skillsAvailable, sandboxMode)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": response,
|
||||
"skills_available": skillsAvailable,
|
||||
"success": true,
|
||||
"data": response,
|
||||
// Skills can be selected before a workspace sandbox is configured; the
|
||||
// execution path remains disabled until the agent chooses a config.
|
||||
"skills_available": true,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -393,6 +393,7 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {
|
|||
}{
|
||||
{http.MethodGet, "/api/v1/sandbox-configs"},
|
||||
{http.MethodPost, "/api/v1/sandbox-configs"},
|
||||
{http.MethodPost, "/api/v1/sandbox-configs/templates/query"},
|
||||
{http.MethodGet, "/api/v1/sandbox-configs/:id"},
|
||||
{http.MethodPut, "/api/v1/sandbox-configs/:id"},
|
||||
{http.MethodDelete, "/api/v1/sandbox-configs/:id"},
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ func RegisterSandboxConfigRoutes(
|
|||
{
|
||||
configs.GET("", g.Viewer(), h.List)
|
||||
configs.PUT("/workspace-policy", g.Admin(), h.SetWorkspacePolicy)
|
||||
configs.POST("/templates/query", g.Admin(), h.QueryTemplates)
|
||||
configs.POST("", g.Admin(), h.Create)
|
||||
configs.GET("/:id", g.Viewer(), h.Get)
|
||||
configs.PUT("/:id", g.Admin(), h.Update)
|
||||
|
|
|
|||
|
|
@ -16,9 +16,6 @@ import (
|
|||
// 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 {
|
||||
|
|
@ -28,20 +25,22 @@ func TestNewRemoteClientForCheckRefusesLinkLocalAtDial(t *testing.T) {
|
|||
{
|
||||
name: "cube",
|
||||
cfg: &Config{
|
||||
Type: SandboxTypeCube,
|
||||
CubeAPIURL: metadata,
|
||||
CubeProxyURL: metadata,
|
||||
CubeSandboxDomain: "cube.app",
|
||||
CubeTemplate: "tpl-test",
|
||||
AllowPrivateEndpoints: true,
|
||||
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",
|
||||
AllowPrivateEndpoints: true,
|
||||
Type: SandboxTypeE2B,
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: metadata,
|
||||
E2BTemplate: "base",
|
||||
},
|
||||
},
|
||||
} {
|
||||
|
|
|
|||
|
|
@ -1,65 +0,0 @@
|
|||
// 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
|
||||
}
|
||||
|
|
@ -25,7 +25,8 @@ import (
|
|||
// SandboxIdentity is the comparable projection of a config: two configs with
|
||||
// equal identities can operate each other's sandboxes.
|
||||
type SandboxIdentity struct {
|
||||
Provider string
|
||||
Provider string
|
||||
AllowPrivateEndpoints bool
|
||||
|
||||
// Control plane - whether an existing sandbox can still be reclaimed.
|
||||
APIURL string
|
||||
|
|
@ -53,7 +54,10 @@ func IdentityOf(tenantCfg *types.TenantSandboxConfig) SandboxIdentity {
|
|||
if tenantCfg == nil {
|
||||
return SandboxIdentity{}
|
||||
}
|
||||
identity := SandboxIdentity{Provider: tenantCfg.SandboxType}
|
||||
identity := SandboxIdentity{
|
||||
Provider: tenantCfg.SandboxType,
|
||||
AllowPrivateEndpoints: tenantCfg.AllowPrivateEndpoints,
|
||||
}
|
||||
switch SandboxType(tenantCfg.SandboxType) {
|
||||
case SandboxTypeCube:
|
||||
if cube := tenantCfg.Cube; cube != nil {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import (
|
|||
|
||||
// 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_*.
|
||||
// without reaching for process-level sandbox configuration.
|
||||
func TestIdentityOfReadsStoredFieldsOnly(t *testing.T) {
|
||||
identity := IdentityOf(&types.TenantSandboxConfig{
|
||||
SandboxType: "e2b",
|
||||
|
|
|
|||
|
|
@ -1,11 +1,8 @@
|
|||
// 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.
|
||||
// A named config is self-contained. Every value the provider client cannot
|
||||
// synthesize has to be present in the workspace config itself, so this file
|
||||
// names those values once and both save and resolve paths check against it.
|
||||
//
|
||||
// Two classes are deliberately NOT required:
|
||||
//
|
||||
|
|
@ -33,8 +30,8 @@ var ErrSandboxConfigIncomplete = errors.New("sandbox: config is missing required
|
|||
|
||||
// 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.
|
||||
// message can be surfaced without translation. Local and disabled hold no
|
||||
// backend-specific values; Docker must explicitly name its image.
|
||||
func MissingRequiredFields(cfg *Config) []string {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
|
|
@ -54,6 +51,8 @@ func MissingRequiredFields(cfg *Config) []string {
|
|||
case SandboxTypeE2B:
|
||||
require("api_key", cfg.E2BAPIKey)
|
||||
require("template_id", cfg.E2BTemplate)
|
||||
case SandboxTypeDocker:
|
||||
require("image", cfg.DockerImage)
|
||||
}
|
||||
return missing
|
||||
}
|
||||
|
|
|
|||
|
|
@ -141,6 +141,58 @@ func (c *CubeRemoteClient) Health(ctx context.Context) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (c *CubeRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplate, error) {
|
||||
items, err := c.client.ListTemplates(ctx)
|
||||
if err != nil {
|
||||
return nil, normalizeCubeError("ListTemplates", err)
|
||||
}
|
||||
result := make([]RemoteTemplate, 0, len(items))
|
||||
for _, item := range items {
|
||||
name := strings.TrimSpace(item.Name)
|
||||
if name == "" {
|
||||
name = item.TemplateID
|
||||
}
|
||||
result = append(result, RemoteTemplate{
|
||||
ID: item.TemplateID,
|
||||
Name: name,
|
||||
Status: item.Status,
|
||||
Version: item.Version,
|
||||
Image: item.ImageInfo,
|
||||
CreatedAt: item.CreatedAt,
|
||||
Standard: isStandardTemplate(name),
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *CubeRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
|
||||
items, err := c.ListTemplates(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range items {
|
||||
if items[i].Standard {
|
||||
return &items[i], nil
|
||||
}
|
||||
}
|
||||
job, err := c.client.BuildTemplate(ctx, cubesandbox.BuildTemplateOptions{
|
||||
Image: DefaultDockerImage,
|
||||
Name: StandardTemplateName,
|
||||
WritableLayerSize: "1G",
|
||||
ExposedPorts: []uint16{49983},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, normalizeCubeError("EnsureStandardTemplate", err)
|
||||
}
|
||||
return &RemoteTemplate{
|
||||
ID: job.TemplateID,
|
||||
Name: StandardTemplateName,
|
||||
Status: job.Status,
|
||||
Image: DefaultDockerImage,
|
||||
Standard: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *CubeRemoteClient) Create(
|
||||
ctx context.Context,
|
||||
request RemoteCreateRequest,
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ import (
|
|||
// One instance lives for the process; clients built from it come and go.
|
||||
type CubeTransportPool struct {
|
||||
control http.RoundTripper
|
||||
policy OutboundURLPolicy
|
||||
|
||||
// data maps a proxy "host:port" to the transport that dials it.
|
||||
data sync.Map
|
||||
|
|
@ -43,10 +44,14 @@ type CubeTransportPool struct {
|
|||
// NewCubeTransportPool returns a pool whose control plane rides control.
|
||||
// A nil control transport installs a guarded one.
|
||||
func NewCubeTransportPool(control http.RoundTripper) *CubeTransportPool {
|
||||
return NewCubeTransportPoolWithPolicy(control, DefaultOutboundURLPolicy())
|
||||
}
|
||||
|
||||
func NewCubeTransportPoolWithPolicy(control http.RoundTripper, policy OutboundURLPolicy) *CubeTransportPool {
|
||||
if control == nil {
|
||||
control = NewGuardedTransport()
|
||||
control = NewGuardedTransportWithPolicy(policy)
|
||||
}
|
||||
return &CubeTransportPool{control: control}
|
||||
return &CubeTransportPool{control: control, policy: policy}
|
||||
}
|
||||
|
||||
// RoundTripperFor returns the transport a client built from cfg should use.
|
||||
|
|
@ -68,7 +73,7 @@ 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))
|
||||
actual, _ := p.data.LoadOrStore(target, newCubeDataTransportWithPolicy(target, p.policy))
|
||||
return actual.(http.RoundTripper)
|
||||
}
|
||||
|
||||
|
|
@ -76,10 +81,14 @@ func (p *CubeTransportPool) dataTransport(target string) http.RoundTripper {
|
|||
// mirroring the SDK's proxy rewrite while adding the outbound address guard
|
||||
// the SDK has no notion of.
|
||||
func newCubeDataTransport(target string) *http.Transport {
|
||||
return newCubeDataTransportWithPolicy(target, DefaultOutboundURLPolicy())
|
||||
}
|
||||
|
||||
func newCubeDataTransportWithPolicy(target string, policy OutboundURLPolicy) *http.Transport {
|
||||
dialer := &net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
Control: SafeDialControl,
|
||||
Control: SafeDialControlForPolicy(policy),
|
||||
}
|
||||
return &http.Transport{
|
||||
// The proxy is addressed directly; an ambient HTTP proxy would
|
||||
|
|
|
|||
|
|
@ -36,8 +36,6 @@ func (c *countingRoundTripper) seen() []string {
|
|||
// 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
|
||||
|
|
@ -51,10 +49,12 @@ func TestCubeTransportPoolRoutesDataPlaneThroughProxy(t *testing.T) {
|
|||
t.Cleanup(proxy.Close)
|
||||
|
||||
cfg := testConfig(t, api)
|
||||
cfg.AllowPrivateEndpoints = true
|
||||
cfg.CubeProxyURL = proxy.URL
|
||||
|
||||
control := &countingRoundTripper{next: NewGuardedTransport()}
|
||||
client, err := NewCubeRemoteClientWithPool(cfg, NewCubeTransportPool(control))
|
||||
policy := OutboundURLPolicy{AllowPrivate: true}
|
||||
control := &countingRoundTripper{next: NewGuardedTransportWithPolicy(policy)}
|
||||
client, err := NewCubeRemoteClientWithPool(cfg, NewCubeTransportPoolWithPolicy(control, policy))
|
||||
require.NoError(t, err)
|
||||
|
||||
ctx := context.Background()
|
||||
|
|
@ -91,7 +91,10 @@ func TestCubeTransportPoolRoutesDataPlaneThroughProxy(t *testing.T) {
|
|||
// 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())
|
||||
pool := NewCubeTransportPoolWithPolicy(
|
||||
NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),
|
||||
OutboundURLPolicy{AllowPrivate: true},
|
||||
)
|
||||
|
||||
first := pool.RoundTripperFor(&Config{
|
||||
CubeProxyURL: "http://127.0.0.1:8080",
|
||||
|
|
|
|||
|
|
@ -1,189 +0,0 @@
|
|||
// 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
|
||||
}
|
||||
}
|
||||
|
|
@ -60,6 +60,12 @@ func (s *DockerSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*Ex
|
|||
// Create context with timeout
|
||||
execCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
// Managers are resolved from workspace configuration on demand, so an
|
||||
// asynchronous pre-pull would race the first execution and start duplicate
|
||||
// pulls on every resolve. Make image readiness part of the execution result.
|
||||
if err := s.EnsureImage(execCtx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Build docker run command
|
||||
args := s.buildDockerArgs(config)
|
||||
|
|
@ -195,8 +201,6 @@ func (s *DockerSandbox) ImageExists(ctx context.Context) bool {
|
|||
}
|
||||
|
||||
// EnsureImage pulls the Docker image if it doesn't exist locally.
|
||||
// This is intended to be called during initialization so the image is
|
||||
// ready before the first script execution.
|
||||
func (s *DockerSandbox) EnsureImage(ctx context.Context) error {
|
||||
if s.ImageExists(ctx) {
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -197,11 +197,11 @@ func TestE2BIntegrationLifecycleParity(t *testing.T) {
|
|||
func e2bIntegrationConfig(t *testing.T) *Config {
|
||||
t.Helper()
|
||||
apiKey := firstNonEmptyEnvironment(
|
||||
"WEKNORA_SANDBOX_E2B_API_KEY",
|
||||
"E2B_INTEGRATION_API_KEY",
|
||||
"E2B_API_KEY",
|
||||
)
|
||||
template := firstNonEmptyEnvironment(
|
||||
"WEKNORA_SANDBOX_E2B_TEMPLATE",
|
||||
"E2B_INTEGRATION_TEMPLATE",
|
||||
"E2B_TEMPLATE",
|
||||
)
|
||||
if apiKey == "" || template == "" {
|
||||
|
|
@ -212,8 +212,8 @@ func e2bIntegrationConfig(t *testing.T) *Config {
|
|||
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.E2BAPIURL = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_API_URL"))
|
||||
cfg.E2BSandboxDomain = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_SANDBOX_DOMAIN"))
|
||||
cfg.E2BTemplate = template
|
||||
cfg.E2BSandboxTTL = e2bIntegrationTTL
|
||||
cfg.E2BHTTPTimeout = e2bIntegrationHTTPTimeout
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ import (
|
|||
|
||||
"connectrpc.com/connect"
|
||||
e2b "github.com/matiasinsaurralde/go-e2b"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// E2BRemoteClient implements RemoteSandboxClient on top of the go-e2b client.
|
||||
|
|
@ -127,6 +129,191 @@ func (c *E2BRemoteClient) Health(ctx context.Context) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (c *E2BRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplate, error) {
|
||||
items, err := c.client.ListTemplates(ctx)
|
||||
if err != nil {
|
||||
return nil, normalizeE2BError("ListTemplates", err)
|
||||
}
|
||||
result := make([]RemoteTemplate, 0, len(items))
|
||||
for _, item := range items {
|
||||
name := item.TemplateID
|
||||
if len(item.Names) > 0 && strings.TrimSpace(item.Names[0]) != "" {
|
||||
name = strings.TrimSpace(item.Names[0])
|
||||
} else if len(item.Aliases) > 0 && strings.TrimSpace(item.Aliases[0]) != "" {
|
||||
name = strings.TrimSpace(item.Aliases[0])
|
||||
}
|
||||
standard := isStandardTemplate(name)
|
||||
for _, candidate := range append(append([]string(nil), item.Aliases...), item.Names...) {
|
||||
if isStandardTemplate(candidate) {
|
||||
standard = true
|
||||
break
|
||||
}
|
||||
}
|
||||
status := normalizeE2BTemplateBuildStatus(item.BuildStatus)
|
||||
// E2B's template list keeps reporting a pending build status after the
|
||||
// template already became spawnable, so reconcile our standard template
|
||||
// against the build endpoints before telling the UI to keep waiting
|
||||
// forever. Limit these extra requests to the standard template; polling
|
||||
// every public template would turn one catalog refresh into an
|
||||
// unbounded N+1 request pattern.
|
||||
if standard && isE2BTemplateBuildPending(status) {
|
||||
if reconciled := c.reconcileE2BTemplateStatus(ctx, item); reconciled != "" {
|
||||
status = reconciled
|
||||
}
|
||||
}
|
||||
result = append(result, RemoteTemplate{
|
||||
ID: item.TemplateID,
|
||||
Name: name,
|
||||
Status: status,
|
||||
Version: item.EnvdVersion,
|
||||
CreatedAt: item.CreatedAt,
|
||||
UpdatedAt: item.UpdatedAt,
|
||||
Standard: standard,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// reconcileE2BTemplateStatus resolves the real build state of a template whose
|
||||
// list entry still looks pending, by asking the per-build endpoint that owns
|
||||
// that answer.
|
||||
//
|
||||
// Only the template's *current* build counts as evidence. E2B spawns from that
|
||||
// build alone, so neither an older successful build nor a non-zero spawn count
|
||||
// proves the template can boot now — both happily coexist with a template that
|
||||
// answers every sandbox creation with a 404. It returns an empty string when
|
||||
// nothing more authoritative than the list status could be established.
|
||||
func (c *E2BRemoteClient) reconcileE2BTemplateStatus(
|
||||
ctx context.Context,
|
||||
item e2b.TemplateDetail,
|
||||
) string {
|
||||
templateID := strings.TrimSpace(item.TemplateID)
|
||||
buildID := strings.TrimSpace(item.BuildID)
|
||||
if templateID == "" {
|
||||
return ""
|
||||
}
|
||||
// buildID is "the last successful build", so the all-zero UUID means the
|
||||
// provider sees none under the tag it resolves. When builds did finish, the
|
||||
// template is not building at all — its builds are untagged, and no amount
|
||||
// of waiting will change that.
|
||||
if isBlankE2BUUID(buildID) {
|
||||
if item.BuildCount > 0 && c.hasSuccessfulE2BBuild(ctx, templateID) {
|
||||
return TemplateStatusUntagged
|
||||
}
|
||||
return ""
|
||||
}
|
||||
build, err := c.client.GetBuildStatus(ctx, templateID, buildID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx,
|
||||
"e2b build status lookup failed for template %s build %s: %v",
|
||||
templateID, buildID, err,
|
||||
)
|
||||
return ""
|
||||
}
|
||||
if isE2BTemplateBuildPending(build.Status) {
|
||||
return ""
|
||||
}
|
||||
reconciled := normalizeE2BTemplateBuildStatus(build.Status)
|
||||
if reconciled == "" {
|
||||
return ""
|
||||
}
|
||||
logger.Debugf(ctx,
|
||||
"e2b template %s list status %q reconciled to %q from build %s",
|
||||
templateID, item.BuildStatus, reconciled, buildID,
|
||||
)
|
||||
return reconciled
|
||||
}
|
||||
|
||||
// hasSuccessfulE2BBuild reports whether the template's build history contains a
|
||||
// finished build. It separates "the first build is still running" from "builds
|
||||
// succeeded but none is reachable under the default tag".
|
||||
func (c *E2BRemoteClient) hasSuccessfulE2BBuild(ctx context.Context, templateID string) bool {
|
||||
result, err := c.client.GetTemplate(ctx, templateID, e2b.WithTemplateBuildsLimit(100))
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "e2b template build history lookup failed for %s: %v", templateID, err)
|
||||
return false
|
||||
}
|
||||
for _, build := range result.Template.Builds {
|
||||
if normalizeE2BTemplateBuildStatus(build.Status) == "ready" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isBlankE2BUUID reports whether id carries no build reference. E2B returns the
|
||||
// all-zero UUID, not an empty string, for a template without a build.
|
||||
func isBlankE2BUUID(id string) bool {
|
||||
trimmed := strings.TrimSpace(id)
|
||||
if trimmed == "" {
|
||||
return true
|
||||
}
|
||||
for _, char := range trimmed {
|
||||
if char != '0' && char != '-' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func normalizeE2BTemplateBuildStatus(status string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(status)) {
|
||||
case "ready", "success", "succeeded", "complete", "completed":
|
||||
return "ready"
|
||||
case "building", "processing":
|
||||
return "building"
|
||||
case "waiting", "queued", "pending", "uploaded":
|
||||
return "waiting"
|
||||
case "error", "failed", "failure", "cancelled", "canceled":
|
||||
return "error"
|
||||
default:
|
||||
return strings.ToLower(strings.TrimSpace(status))
|
||||
}
|
||||
}
|
||||
|
||||
func isE2BTemplateBuildPending(status string) bool {
|
||||
switch normalizeE2BTemplateBuildStatus(status) {
|
||||
case "building", "waiting":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *E2BRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
|
||||
items, err := c.ListTemplates(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range items {
|
||||
if items[i].Standard {
|
||||
return &items[i], nil
|
||||
}
|
||||
}
|
||||
builder := e2b.NewTemplate().FromImage(DefaultDockerImage)
|
||||
build, err := builder.BuildInBackground(ctx, c.client, e2b.BuildConfig{
|
||||
Name: StandardTemplateName,
|
||||
// Creating a sandbox from a plain template name or ID resolves the
|
||||
// "default" tag, so a build tagged anything else is unreachable: E2B
|
||||
// answers every creation with "tag 'default' does not exist for
|
||||
// template ...". Naming the tag explicitly keeps that contract visible
|
||||
// instead of relying on the server-side default.
|
||||
Tags: []string{DefaultE2BTemplateTag},
|
||||
CPUCount: 2,
|
||||
MemoryMB: 2048,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, normalizeE2BError("EnsureStandardTemplate", err)
|
||||
}
|
||||
return &RemoteTemplate{
|
||||
ID: build.TemplateID,
|
||||
Name: StandardTemplateName,
|
||||
Status: "building",
|
||||
Image: DefaultDockerImage,
|
||||
Standard: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *E2BRemoteClient) Create(
|
||||
ctx context.Context,
|
||||
request RemoteCreateRequest,
|
||||
|
|
@ -807,6 +994,7 @@ func normalizeE2BError(op string, err error) error {
|
|||
return fmt.Errorf("e2b %s: %w", op, err)
|
||||
}
|
||||
kind := RemoteErrorKindInternal
|
||||
status := 0
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
kind = RemoteErrorKindTimeout
|
||||
|
|
@ -839,6 +1027,7 @@ func normalizeE2BError(op string, err error) error {
|
|||
kind = RemoteErrorKindTimeout
|
||||
case errors.As(err, &apiErr):
|
||||
kind = httpErrorKind(op, apiErr.StatusCode)
|
||||
status = apiErr.StatusCode
|
||||
case errors.As(err, &connectErr):
|
||||
switch connectErr.Code() {
|
||||
case connect.CodeCanceled, connect.CodeDeadlineExceeded:
|
||||
|
|
@ -868,7 +1057,9 @@ func normalizeE2BError(op string, err error) error {
|
|||
}
|
||||
}
|
||||
}
|
||||
return NewRemoteError(SandboxTypeE2B, op, kind, err.Error(), err)
|
||||
remoteErr := NewRemoteError(SandboxTypeE2B, op, kind, err.Error(), err)
|
||||
remoteErr.StatusCode = status
|
||||
return remoteErr
|
||||
}
|
||||
|
||||
// e2bRemoteEntryType maps the E2B SDK FileInfo.Type onto the provider-neutral
|
||||
|
|
|
|||
|
|
@ -269,6 +269,307 @@ func TestE2BRemoteClientProviderAndCapabilities(t *testing.T) {
|
|||
require.True(t, caps.SupportsFilesystemEnumeration)
|
||||
}
|
||||
|
||||
func TestE2BRemoteClientListTemplatesReconcilesStandardTemplateBuildStatus(t *testing.T) {
|
||||
var statusRequests atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{{
|
||||
"templateID": "template-ready",
|
||||
"buildID": "build-success",
|
||||
"names": []string{"project/weknora"},
|
||||
"aliases": []string{"weknora"},
|
||||
"buildStatus": "waiting",
|
||||
"envdVersion": "0.4.0",
|
||||
}})
|
||||
case "/templates/template-ready/builds/build-success/status":
|
||||
statusRequests.Add(1)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-ready",
|
||||
"buildID": "build-success",
|
||||
"status": "ready",
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BTemplate: "template-ready",
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
templates, err := client.ListTemplates(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, templates, 1)
|
||||
require.True(t, templates[0].Standard)
|
||||
require.Equal(t, "project/weknora", templates[0].Name)
|
||||
require.Equal(t, "ready", templates[0].Status)
|
||||
require.Equal(t, int32(1), statusRequests.Load())
|
||||
}
|
||||
|
||||
// An older successful build does not make the current one spawnable: E2B boots
|
||||
// the current build only, and reporting "ready" here let the UI hand out a
|
||||
// template that every sandbox creation rejected with a 404.
|
||||
func TestE2BRemoteClientListTemplatesIgnoresOlderSuccessfulBuild(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{{
|
||||
"templateID": "template-queued",
|
||||
"buildID": "build-queued",
|
||||
"names": []string{"project/weknora"},
|
||||
"buildStatus": "waiting",
|
||||
}})
|
||||
case "/templates/template-queued/builds/build-queued/status":
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-queued",
|
||||
"buildID": "build-queued",
|
||||
"status": "waiting",
|
||||
})
|
||||
case "/templates/template-queued":
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-queued",
|
||||
"names": []string{"project/weknora"},
|
||||
"builds": []map[string]any{
|
||||
{"buildID": "build-queued", "status": "waiting"},
|
||||
{"buildID": "build-older", "status": "success"},
|
||||
},
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
templates, err := client.ListTemplates(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, templates, 1)
|
||||
require.Equal(t, "waiting", templates[0].Status)
|
||||
}
|
||||
|
||||
// E2B reports the all-zero UUID for a template that never got a build attached.
|
||||
// Asking the build endpoint about it only yields a 400, and the template cannot
|
||||
// be spawned, so the pending list status stands.
|
||||
func TestE2BRemoteClientListTemplatesKeepsPendingWithoutBuildReference(t *testing.T) {
|
||||
var buildRequests atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{{
|
||||
"templateID": "template-unbuilt",
|
||||
"buildID": "00000000-0000-0000-0000-000000000000",
|
||||
"names": []string{"project/weknora"},
|
||||
"buildStatus": "building",
|
||||
"spawnCount": 0,
|
||||
}})
|
||||
case strings.Contains(r.URL.Path, "/builds/"):
|
||||
buildRequests.Add(1)
|
||||
http.Error(w, `{"code":400,"message":"Build not found"}`, http.StatusBadRequest)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
templates, err := client.ListTemplates(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, templates, 1)
|
||||
require.Equal(t, "building", templates[0].Status)
|
||||
require.Equal(t, int32(0), buildRequests.Load())
|
||||
}
|
||||
|
||||
func TestE2BRemoteClientListTemplatesKeepsPendingWithoutSuccessfulBuild(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{{
|
||||
"templateID": "template-fresh",
|
||||
"buildID": "build-fresh",
|
||||
"names": []string{"project/weknora"},
|
||||
"buildStatus": "building",
|
||||
}})
|
||||
case "/templates/template-fresh/builds/build-fresh/status":
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-fresh",
|
||||
"buildID": "build-fresh",
|
||||
"status": "building",
|
||||
})
|
||||
case "/templates/template-fresh":
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-fresh",
|
||||
"builds": []map[string]any{
|
||||
{"buildID": "build-fresh", "status": "building"},
|
||||
},
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
templates, err := client.ListTemplates(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, templates, 1)
|
||||
require.Equal(t, "building", templates[0].Status)
|
||||
}
|
||||
|
||||
// Builds that finished but carry no default tag look exactly like "still
|
||||
// building" in the template list, while sandbox creation rejects the template
|
||||
// outright. The catalog has to name that state so the UI stops waiting.
|
||||
func TestE2BRemoteClientListTemplatesReportsUntaggedBuilds(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{{
|
||||
"templateID": "template-untagged",
|
||||
"buildID": "00000000-0000-0000-0000-000000000000",
|
||||
"names": []string{"project/weknora"},
|
||||
"buildStatus": "waiting",
|
||||
"buildCount": 2,
|
||||
}})
|
||||
case "/templates/template-untagged":
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-untagged",
|
||||
"builds": []map[string]any{
|
||||
{"buildID": "build-1", "status": "success"},
|
||||
{"buildID": "build-2", "status": "success"},
|
||||
},
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
templates, err := client.ListTemplates(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, templates, 1)
|
||||
require.Equal(t, TemplateStatusUntagged, templates[0].Status)
|
||||
}
|
||||
|
||||
// A template whose first build is genuinely still running has no finished build
|
||||
// to find, so it must keep reporting the pending status.
|
||||
func TestE2BRemoteClientListTemplatesKeepsPendingOnFirstBuild(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{{
|
||||
"templateID": "template-first",
|
||||
"buildID": "00000000-0000-0000-0000-000000000000",
|
||||
"names": []string{"project/weknora"},
|
||||
"buildStatus": "building",
|
||||
"buildCount": 1,
|
||||
}})
|
||||
case "/templates/template-first":
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-first",
|
||||
"builds": []map[string]any{{"buildID": "build-1", "status": "building"}},
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
templates, err := client.ListTemplates(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, templates, 1)
|
||||
require.Equal(t, "building", templates[0].Status)
|
||||
}
|
||||
|
||||
// Past spawns say nothing about the build that is current now, so they must not
|
||||
// upgrade a pending status either.
|
||||
func TestE2BRemoteClientListTemplatesIgnoresSpawnCount(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/templates":
|
||||
writeJSON(w, http.StatusOK, []map[string]any{{
|
||||
"templateID": "template-spawned",
|
||||
"buildID": "build-x",
|
||||
"names": []string{"weknora"},
|
||||
"buildStatus": "waiting",
|
||||
"spawnCount": 4,
|
||||
}})
|
||||
case "/templates/template-spawned/builds/build-x/status":
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"templateID": "template-spawned",
|
||||
"buildID": "build-x",
|
||||
"status": "waiting",
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client, err := NewE2BRemoteClient(&Config{
|
||||
E2BAPIKey: "key-test",
|
||||
E2BAPIURL: server.URL,
|
||||
E2BSandboxTTL: time.Minute,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
templates, err := client.ListTemplates(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, templates, 1)
|
||||
require.Equal(t, "waiting", templates[0].Status)
|
||||
}
|
||||
|
||||
func TestNormalizeE2BTemplateBuildStatus(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"READY": "ready",
|
||||
"success": "ready",
|
||||
"completed": "ready",
|
||||
"processing": "building",
|
||||
"uploaded": "waiting",
|
||||
"failed": "error",
|
||||
"custom": "custom",
|
||||
}
|
||||
for raw, want := range tests {
|
||||
require.Equalf(t, want, normalizeE2BTemplateBuildStatus(raw), "status %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestE2BRemoteClientCreateWritesMetadataAndPauseLifecycle(t *testing.T) {
|
||||
mock := newE2BMockServer(t)
|
||||
client := newTestE2BRemoteClient(t, mock)
|
||||
|
|
|
|||
|
|
@ -51,14 +51,6 @@ func (m *DefaultManager) initializeSandbox(ctx context.Context) error {
|
|||
dockerSandbox := NewDockerSandbox(m.config)
|
||||
if dockerSandbox.IsAvailable(ctx) {
|
||||
m.sandbox = dockerSandbox
|
||||
// Pre-pull the sandbox image asynchronously so it's ready before first use
|
||||
go func() {
|
||||
if err := dockerSandbox.EnsureImage(context.Background()); err != nil {
|
||||
log.Printf("[sandbox] failed to pre-pull image %s: %v", m.config.DockerImage, err)
|
||||
} else {
|
||||
log.Printf("[sandbox] image %s is ready", m.config.DockerImage)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -106,9 +98,19 @@ func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*E
|
|||
return nil, ErrSandboxDisabled
|
||||
}
|
||||
|
||||
effective := config
|
||||
if config != nil && len(m.config.EnvVars) > 0 {
|
||||
copy := *config
|
||||
copy.Env = cloneMetadata(m.config.EnvVars)
|
||||
for key, value := range config.Env {
|
||||
copy.Env[key] = value
|
||||
}
|
||||
effective = ©
|
||||
}
|
||||
|
||||
// Perform security validation unless explicitly skipped
|
||||
if !config.SkipValidation {
|
||||
if err := runScriptValidation(m.validator, config); err != nil {
|
||||
if effective != nil && !effective.SkipValidation {
|
||||
if err := runScriptValidation(m.validator, effective); err != nil {
|
||||
log.Printf("[sandbox] Security validation failed: %v", err)
|
||||
return &ExecuteResult{
|
||||
ExitCode: -1,
|
||||
|
|
@ -118,7 +120,7 @@ func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*E
|
|||
}
|
||||
}
|
||||
|
||||
return sandbox.Execute(ctx, config)
|
||||
return sandbox.Execute(ctx, effective)
|
||||
}
|
||||
|
||||
// runScriptValidation is the package-level helper that DefaultManager and
|
||||
|
|
|
|||
|
|
@ -18,8 +18,7 @@ import (
|
|||
)
|
||||
|
||||
// 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.
|
||||
// stored SandboxType strings so wiring/logging stays uniform.
|
||||
type RemoteProvider = SandboxType
|
||||
|
||||
// RemoteSandboxHandle is an opaque, provider-issued reference to a live
|
||||
|
|
|
|||
|
|
@ -82,6 +82,12 @@ type RemoteError struct {
|
|||
// or SDK error strings belong here.
|
||||
Message string
|
||||
|
||||
// StatusCode is the provider's HTTP status when the failure came from an
|
||||
// HTTP response, or 0 when it did not. Kind deliberately collapses statuses
|
||||
// that call for the same lifecycle decision, so diagnostics that must tell
|
||||
// those statuses apart read this instead of re-parsing Message.
|
||||
StatusCode int
|
||||
|
||||
// Cause is the original provider-side error, retained for
|
||||
// errors.Unwrap so callers can still errors.Is / errors.As it.
|
||||
Cause error
|
||||
|
|
|
|||
|
|
@ -0,0 +1,27 @@
|
|||
package sandbox
|
||||
|
||||
// Runtime tuning has safe built-in defaults. Unlike endpoints, credentials,
|
||||
// and templates, these values do not identify an external backend.
|
||||
func applyCubeRuntimeDefaults(cfg *Config) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if cfg.CubeSandboxTTL <= 0 {
|
||||
cfg.CubeSandboxTTL = DefaultCubeSandboxTTL
|
||||
}
|
||||
if cfg.CubeHTTPTimeout <= 0 {
|
||||
cfg.CubeHTTPTimeout = DefaultCubeHTTPTimeout
|
||||
}
|
||||
}
|
||||
|
||||
func applyE2BRuntimeDefaults(cfg *Config) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
if cfg.E2BSandboxTTL <= 0 {
|
||||
cfg.E2BSandboxTTL = DefaultE2BSandboxTTL
|
||||
}
|
||||
if cfg.E2BHTTPTimeout <= 0 {
|
||||
cfg.E2BHTTPTimeout = DefaultE2BHTTPTimeout
|
||||
}
|
||||
}
|
||||
|
|
@ -29,12 +29,11 @@ const (
|
|||
)
|
||||
|
||||
// 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.
|
||||
// named sandbox backend. Remote backends are session-persistent; docker/local
|
||||
// are stateless, but all four share the same workspace configuration surface.
|
||||
func IsNamedSandboxBackendType(raw string) bool {
|
||||
switch SandboxType(raw) {
|
||||
case SandboxTypeCube, SandboxTypeE2B:
|
||||
case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker, SandboxTypeLocal:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
|
@ -48,8 +47,8 @@ const (
|
|||
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 is retained for SDK tests and explicit local helpers;
|
||||
// workspace configs must still provide their endpoint.
|
||||
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.
|
||||
|
|
@ -57,8 +56,6 @@ const (
|
|||
// 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.
|
||||
|
|
@ -200,6 +197,10 @@ type Config struct {
|
|||
// DefaultTimeout is the default execution timeout
|
||||
DefaultTimeout time.Duration
|
||||
|
||||
// AllowPrivateEndpoints is the per-workspace outbound policy for this
|
||||
// connection. Link-local addresses are blocked regardless.
|
||||
AllowPrivateEndpoints bool
|
||||
|
||||
// DockerImage is the Docker image to use (Docker sandbox only)
|
||||
DockerImage string
|
||||
|
||||
|
|
@ -270,11 +271,9 @@ type Config struct {
|
|||
|
||||
// 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.
|
||||
// It deliberately carries no Cube or E2B endpoint, credential or template:
|
||||
// those belong to a named workspace config. Presetting them here once meant an
|
||||
// incomplete workspace config could silently dial localhost.
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
Type: SandboxTypeLocal,
|
||||
|
|
|
|||
|
|
@ -122,6 +122,39 @@ echo "Args: $@"
|
|||
t.Logf("Duration: %v", result.Duration)
|
||||
}
|
||||
|
||||
func TestManagerMergesWorkspaceEnvironmentVariables(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
scriptPath := filepath.Join(tmpDir, "env.sh")
|
||||
scriptContent := "#!/bin/sh\nprintf '%s|%s' \"$WORKSPACE_VALUE\" \"$OVERRIDE_VALUE\"\n"
|
||||
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
config := DefaultConfig()
|
||||
config.Type = SandboxTypeLocal
|
||||
config.EnvVars = map[string]string{
|
||||
"WORKSPACE_VALUE": "from-workspace",
|
||||
"OVERRIDE_VALUE": "workspace-default",
|
||||
}
|
||||
manager, err := NewManager(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := manager.Execute(context.Background(), &ExecuteConfig{
|
||||
Script: scriptPath,
|
||||
ScriptContent: scriptContent,
|
||||
Env: map[string]string{"OVERRIDE_VALUE": "per-execution"},
|
||||
Timeout: 10 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Stdout != "from-workspace|per-execution" {
|
||||
t.Fatalf("unexpected environment output %q", result.Stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalSandboxTimeout(t *testing.T) {
|
||||
// Create a temporary script that sleeps
|
||||
tmpDir, err := os.MkdirTemp("", "sandbox-test")
|
||||
|
|
@ -202,8 +235,8 @@ func TestIsNamedSandboxBackendType(t *testing.T) {
|
|||
}{
|
||||
{"cube", true},
|
||||
{"e2b", true},
|
||||
{"docker", false},
|
||||
{"local", false},
|
||||
{"docker", true},
|
||||
{"local", true},
|
||||
{"disabled", false},
|
||||
{"", false},
|
||||
} {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const StandardTemplateName = "weknora"
|
||||
|
||||
// DefaultE2BTemplateTag is the tag E2B resolves when a sandbox is created from a
|
||||
// bare template name or ID. Builds must carry it to be spawnable at all.
|
||||
const DefaultE2BTemplateTag = "default"
|
||||
|
||||
// TemplateStatusUntagged marks a template whose builds finished but which has no
|
||||
// build under the tag sandbox creation resolves. It looks identical to "still
|
||||
// building" in the provider's template list, yet waiting will never help: the
|
||||
// template needs a new build carrying the default tag.
|
||||
const TemplateStatusUntagged = "untagged"
|
||||
|
||||
// RemoteTemplate is the provider-neutral template projection returned to the
|
||||
// settings UI. IDs remain opaque; users choose a readable name and status.
|
||||
type RemoteTemplate struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Image string `json:"image,omitempty"`
|
||||
CreatedAt string `json:"created_at,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
Standard bool `json:"standard"`
|
||||
}
|
||||
|
||||
// RemoteTemplateCatalog is an optional provider capability used by the
|
||||
// configuration flow. It stays separate from RemoteSandboxClient because the
|
||||
// session lifecycle never needs template administration.
|
||||
type RemoteTemplateCatalog interface {
|
||||
ListTemplates(ctx context.Context) ([]RemoteTemplate, error)
|
||||
EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error)
|
||||
}
|
||||
|
||||
func isStandardTemplate(name string) bool {
|
||||
trimmed := strings.Trim(strings.TrimSpace(name), "/")
|
||||
if strings.EqualFold(trimmed, StandardTemplateName) {
|
||||
return true
|
||||
}
|
||||
parts := strings.Split(trimmed, "/")
|
||||
return len(parts) > 1 && strings.EqualFold(parts[len(parts)-1], StandardTemplateName)
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package sandbox
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsStandardTemplateRecognizesProviderScopedName(t *testing.T) {
|
||||
for _, name := range []string{"weknora", "team/weknora", "project-b89e/WeKnora"} {
|
||||
if !isStandardTemplate(name) {
|
||||
t.Fatalf("expected %q to identify the WeKnora standard template", name)
|
||||
}
|
||||
}
|
||||
if isStandardTemplate("weknora-custom") {
|
||||
t.Fatal("custom template must not be treated as the standard template")
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
//
|
||||
// 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
|
||||
// inherited from process configuration; they come from the workspace 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
|
||||
|
|
@ -15,8 +15,8 @@
|
|||
//
|
||||
// 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.
|
||||
// of a backend's identity. A nil tenant config is used only by low-level
|
||||
// callers that explicitly request the supplied baseline.
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
|
|
@ -58,14 +58,15 @@ func ResolveEffectiveConfig(
|
|||
effective.Type = resolved
|
||||
}
|
||||
overrideSeconds(&effective.DefaultTimeout, tenantCfg.DefaultTimeoutSec)
|
||||
effective.AllowPrivateEndpoints = tenantCfg.AllowPrivateEndpoints
|
||||
if tenantCfg.EnvVars != nil {
|
||||
effective.EnvVars = cloneMetadata(tenantCfg.EnvVars)
|
||||
}
|
||||
if cube := tenantCfg.Cube; cube != nil {
|
||||
if err := overrideURL(&effective.CubeAPIURL, cube.APIURL); err != nil {
|
||||
if err := overrideURL(&effective.CubeAPIURL, cube.APIURL, effective.AllowPrivateEndpoints); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := overrideURL(&effective.CubeProxyURL, cube.ProxyURL); err != nil {
|
||||
if err := overrideURL(&effective.CubeProxyURL, cube.ProxyURL, effective.AllowPrivateEndpoints); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
overrideString(&effective.CubeSandboxDomain, cube.SandboxDomain)
|
||||
|
|
@ -76,7 +77,7 @@ func ResolveEffectiveConfig(
|
|||
}
|
||||
|
||||
if e2bCfg := tenantCfg.E2B; e2bCfg != nil {
|
||||
if err := overrideURL(&effective.E2BAPIURL, e2bCfg.APIURL); err != nil {
|
||||
if err := overrideURL(&effective.E2BAPIURL, e2bCfg.APIURL, effective.AllowPrivateEndpoints); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
overrideString(&effective.E2BSandboxDomain, e2bCfg.SandboxDomain)
|
||||
|
|
@ -110,6 +111,7 @@ func ResolveEffectiveConfig(
|
|||
// 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.DockerImage = ""
|
||||
cfg.CubeAPIURL = ""
|
||||
cfg.CubeProxyURL = ""
|
||||
cfg.CubeSandboxDomain = ""
|
||||
|
|
@ -174,11 +176,11 @@ func overrideString(dst *string, value string) {
|
|||
|
||||
// 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 {
|
||||
func overrideURL(dst *string, value string, allowPrivate bool) error {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
if err := ValidateOutboundURL(value); err != nil {
|
||||
if err := ValidateOutboundURLWithPolicy(value, OutboundURLPolicy{AllowPrivate: allowPrivate}); err != nil {
|
||||
return err
|
||||
}
|
||||
*dst = value
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ type TenantSandboxResolver interface {
|
|||
|
||||
// TenantSandboxResolverDeps bundles the resolver's wiring.
|
||||
type TenantSandboxResolverDeps struct {
|
||||
// GlobalConfig is the process-wide config built from WEKNORA_SANDBOX_*.
|
||||
// GlobalConfig supplies only built-in runtime tuning defaults.
|
||||
GlobalConfig *Config
|
||||
|
||||
// DefaultManager serves tenants without their own configuration, which
|
||||
|
|
@ -91,12 +91,14 @@ type TenantSandboxResolverDeps struct {
|
|||
}
|
||||
|
||||
type tenantSandboxResolver struct {
|
||||
deps TenantSandboxResolverDeps
|
||||
transport *http.Transport
|
||||
deps TenantSandboxResolverDeps
|
||||
transport *http.Transport
|
||||
privateTransport *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
|
||||
cubeTransports *CubeTransportPool
|
||||
privateCubeTransports *CubeTransportPool
|
||||
}
|
||||
|
||||
// NewTenantSandboxResolver validates the wiring and returns a resolver.
|
||||
|
|
@ -118,9 +120,11 @@ func NewTenantSandboxResolver(deps TenantSandboxResolverDeps) (TenantSandboxReso
|
|||
transport = NewGuardedTransport()
|
||||
}
|
||||
return &tenantSandboxResolver{
|
||||
deps: deps,
|
||||
transport: transport,
|
||||
cubeTransports: NewCubeTransportPool(transport),
|
||||
deps: deps,
|
||||
transport: transport,
|
||||
privateTransport: NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),
|
||||
cubeTransports: NewCubeTransportPool(transport),
|
||||
privateCubeTransports: NewCubeTransportPoolWithPolicy(nil, OutboundURLPolicy{AllowPrivate: true}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
@ -128,11 +132,15 @@ func NewTenantSandboxResolver(deps TenantSandboxResolverDeps) (TenantSandboxReso
|
|||
// the outbound policy forbids. This closes the DNS-rebinding window that
|
||||
// save-time URL validation cannot cover.
|
||||
func NewGuardedTransport() *http.Transport {
|
||||
return NewGuardedTransportWithPolicy(DefaultOutboundURLPolicy())
|
||||
}
|
||||
|
||||
func NewGuardedTransportWithPolicy(policy OutboundURLPolicy) *http.Transport {
|
||||
return &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
Control: SafeDialControl,
|
||||
Control: SafeDialControlForPolicy(policy),
|
||||
}).DialContext,
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 4,
|
||||
|
|
@ -148,7 +156,7 @@ func (r *tenantSandboxResolver) Resolve(
|
|||
) (Manager, error) {
|
||||
if strings.TrimSpace(configID) == "" ||
|
||||
configID == types.SandboxConfigIDGlobalDefault {
|
||||
return r.deps.DefaultManager, nil
|
||||
return NewDisabledManager(), nil
|
||||
}
|
||||
|
||||
resolved, err := r.deps.Loader.Load(ctx, tenantID, configID)
|
||||
|
|
@ -184,9 +192,15 @@ func (r *tenantSandboxResolver) Resolve(
|
|||
SkipHealthProbe: true,
|
||||
ConfigID: configID,
|
||||
})
|
||||
case SandboxTypeDocker, SandboxTypeLocal:
|
||||
// Stateless backends still come from the selected workspace row. Docker
|
||||
// fallback is deliberately disabled: silently running a configured
|
||||
// container workload on the application host would cross an isolation
|
||||
// boundary.
|
||||
effective.FallbackEnabled = false
|
||||
return NewManager(effective)
|
||||
default:
|
||||
// docker/local have no per-config remote wiring.
|
||||
return r.deps.DefaultManager, nil
|
||||
return NewDisabledManager(), nil
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -195,8 +209,14 @@ func (r *tenantSandboxResolver) Resolve(
|
|||
func (r *tenantSandboxResolver) buildClient(cfg *Config) (RemoteSandboxClient, error) {
|
||||
switch cfg.Type {
|
||||
case SandboxTypeCube:
|
||||
if cfg.AllowPrivateEndpoints {
|
||||
return NewCubeRemoteClientWithPool(cfg, r.privateCubeTransports)
|
||||
}
|
||||
return NewCubeRemoteClientWithPool(cfg, r.cubeTransports)
|
||||
case SandboxTypeE2B:
|
||||
if cfg.AllowPrivateEndpoints {
|
||||
return NewE2BRemoteClientWithTransport(cfg, r.privateTransport)
|
||||
}
|
||||
return NewE2BRemoteClientWithTransport(cfg, r.transport)
|
||||
default:
|
||||
return nil, fmt.Errorf("sandbox: provider %q has no remote client", cfg.Type)
|
||||
|
|
@ -217,9 +237,11 @@ func NewRemoteClientForCheck(cfg *Config) (RemoteSandboxClient, error) {
|
|||
}
|
||||
switch cfg.Type {
|
||||
case SandboxTypeCube:
|
||||
return NewCubeRemoteClientWithPool(cfg, NewCubeTransportPool(nil))
|
||||
return NewCubeRemoteClientWithPool(cfg, NewCubeTransportPoolWithPolicy(nil,
|
||||
OutboundURLPolicy{AllowPrivate: cfg.AllowPrivateEndpoints}))
|
||||
case SandboxTypeE2B:
|
||||
return NewE2BRemoteClientWithTransport(cfg, NewGuardedTransport())
|
||||
return NewE2BRemoteClientWithTransport(cfg, NewGuardedTransportWithPolicy(
|
||||
OutboundURLPolicy{AllowPrivate: cfg.AllowPrivateEndpoints}))
|
||||
default:
|
||||
return nil, fmt.Errorf("sandbox: provider %q cannot be probed", cfg.Type)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,15 +43,13 @@ func newTestResolver(t *testing.T, loader TenantSandboxConfigLoader) (TenantSand
|
|||
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{})
|
||||
func TestResolveEmptyConfigIDIsDisabled(t *testing.T) {
|
||||
resolver, _ := newTestResolver(t, &stubTenantConfigLoader{})
|
||||
|
||||
mgr, err := resolver.Resolve(context.Background(), 42, "")
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Same(t, fallback, mgr)
|
||||
require.Equal(t, SandboxTypeDisabled, mgr.GetType())
|
||||
}
|
||||
|
||||
// A cordoned config must not produce a manager: the whole point of the cordon
|
||||
|
|
@ -103,6 +101,25 @@ func TestResolveBuildsRemoteManagerWithoutHealthProbe(t *testing.T) {
|
|||
require.Equal(t, SandboxTypeE2B, mgr.GetType())
|
||||
}
|
||||
|
||||
func TestResolveBuildsLocalManagerFromWorkspaceConfig(t *testing.T) {
|
||||
resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{
|
||||
result: ResolvedTenantSandboxConfig{
|
||||
Config: &types.TenantSandboxConfig{
|
||||
SandboxType: "local",
|
||||
DefaultTimeoutSec: 17,
|
||||
EnvVars: map[string]string{"WORKSPACE_FLAG": "enabled"},
|
||||
},
|
||||
Found: true,
|
||||
},
|
||||
})
|
||||
|
||||
mgr, err := resolver.Resolve(context.Background(), 42, "cfg-local")
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotSame(t, fallback, mgr)
|
||||
require.Equal(t, SandboxTypeLocal, 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) {
|
||||
|
|
|
|||
|
|
@ -14,13 +14,9 @@
|
|||
// 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.
|
||||
// Self-hosted deployments complicate this, so private endpoints are an
|
||||
// explicit field on each workspace config. Even when enabled, link-local
|
||||
// ranges — including cloud metadata — stay blocked.
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
|
|
@ -28,8 +24,6 @@ import (
|
|||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
|
@ -38,11 +32,6 @@ import (
|
|||
// 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 {
|
||||
|
|
@ -51,14 +40,10 @@ type OutboundURLPolicy struct {
|
|||
AllowPrivate bool
|
||||
}
|
||||
|
||||
// DefaultOutboundURLPolicy reads the policy from the environment. Absent or
|
||||
// unparseable values fail closed.
|
||||
// DefaultOutboundURLPolicy is the fail-closed policy used by callers that do
|
||||
// not carry a workspace configuration.
|
||||
func DefaultOutboundURLPolicy() OutboundURLPolicy {
|
||||
allow, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(AllowPrivateEndpointsEnv)))
|
||||
if err != nil {
|
||||
allow = false
|
||||
}
|
||||
return OutboundURLPolicy{AllowPrivate: allow}
|
||||
return OutboundURLPolicy{}
|
||||
}
|
||||
|
||||
// ValidateOutboundURL checks raw against the environment's policy.
|
||||
|
|
@ -66,11 +51,21 @@ func ValidateOutboundURL(raw string) error {
|
|||
return DefaultOutboundURLPolicy().Validate(raw)
|
||||
}
|
||||
|
||||
func ValidateOutboundURLWithPolicy(raw string, policy OutboundURLPolicy) error {
|
||||
return policy.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)
|
||||
}
|
||||
|
||||
func SafeDialControlForPolicy(policy OutboundURLPolicy) func(string, string, syscall.RawConn) error {
|
||||
return func(network string, address string, conn syscall.RawConn) error {
|
||||
return policy.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.
|
||||
//
|
||||
|
|
@ -103,8 +98,8 @@ func (p OutboundURLPolicy) Validate(raw string) error {
|
|||
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,
|
||||
"%w: host %q is loopback; enable private endpoints for this workspace config",
|
||||
ErrUnsafeOutboundURL, host,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
|
|
@ -162,8 +157,8 @@ func (p OutboundURLPolicy) checkIP(ip net.IP) error {
|
|||
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,
|
||||
"%w: address %s is private; enable private endpoints for this workspace config",
|
||||
ErrUnsafeOutboundURL, ip,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -137,16 +137,7 @@ func TestPolicyDialControlMirrorsValidation(t *testing.T) {
|
|||
}
|
||||
|
||||
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")
|
||||
t.Fatal("callers without a workspace config must fail closed")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -152,8 +152,7 @@ type CustomAgentConfig struct {
|
|||
|
||||
// ===== Sandbox Settings =====
|
||||
// SandboxConfigID selects which workspace sandbox config this agent's
|
||||
// skill scripts run on. Empty means the deployment-wide
|
||||
// WEKNORA_SANDBOX_* defaults.
|
||||
// skill scripts run on. Empty means sandbox execution is disabled.
|
||||
//
|
||||
// This references the LOGICAL config, never a specific revision: keeping
|
||||
// the indirection here is what would let credential rotation happen
|
||||
|
|
|
|||
|
|
@ -620,25 +620,25 @@ func (c *StorageEngineConfig) Scan(value interface{}) error {
|
|||
|
||||
// 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.
|
||||
// It is self-contained: provider fields are not inherited from process
|
||||
// environment. Leaving a required provider field empty is rejected on save.
|
||||
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
|
||||
// SandboxType selects the sandbox backend. Named configs may use "cube",
|
||||
// "e2b", "docker", or "local". "disabled" is reserved for the hidden
|
||||
// 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 is the per-execution timeout in seconds. 0 uses the
|
||||
// program's built-in default.
|
||||
DefaultTimeoutSec int `json:"default_timeout_sec,omitempty"`
|
||||
|
||||
// AllowPrivateEndpoints permits this workspace config to reach RFC1918 or
|
||||
// loopback cluster endpoints. Link-local/cloud-metadata addresses remain
|
||||
// blocked. It is explicit in the UI instead of hidden in process env.
|
||||
AllowPrivateEndpoints bool `json:"allow_private_endpoints,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
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ import (
|
|||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SandboxConfigIDGlobalDefault marks a sandbox created on the deployment-wide
|
||||
// WEKNORA_SANDBOX_* configuration rather than on a stored config row.
|
||||
// SandboxConfigIDGlobalDefault is retained for sessions created by older
|
||||
// versions that used a deployment-wide sandbox configuration.
|
||||
//
|
||||
// A sentinel rather than the empty string, so NULL on sessions.sandbox_config_id
|
||||
// unambiguously means "this session has no live sandbox".
|
||||
|
|
|
|||
|
|
@ -223,7 +223,7 @@ Lite 模式通过编译期 `EDITION=lite` 与运行期 `.env.lite` 环境实现
|
|||
- **队列/流**:`STREAM_MANAGER_TYPE=memory`(`internal/stream/factory.go`),不需要 Redis,Asynq 分布式队列在 Lite 模式下为内存/no-op;
|
||||
- **前端**:`make build-lite` 会把 `frontend/dist` 复制为仓库根的 `web/`,二进制直接内嵌托管静态资源(`WEKNORA_WEB_DIR` 可指定目录,router 的 `serveFrontendStatic` 提供服务);
|
||||
- **文档解析**:仍可选连本地 docreader(`DOCREADER_ADDR=127.0.0.1:50051`);
|
||||
- **沙箱**:`WEKNORA_SANDBOX_MODE=disabled`。
|
||||
- **沙箱**:Lite 启动时不预置后端;可在设置页按空间统一配置 Docker、Local、CubeSandbox 或 E2B。
|
||||
|
||||
```bash
|
||||
cp .env.lite.example .env.lite # 修改 SYSTEM_AES_KEY / JWT_SECRET
|
||||
|
|
|
|||
|
|
@ -250,8 +250,7 @@ AWS S3 的 `S3_ACCESS_KEY` / `S3_SECRET_KEY` 可以**同时留空**,此时走
|
|||
|
||||
| 名称 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `WEKNORA_SANDBOX_MODE` | disabled(代码默认;标准 compose 里设为 docker) | Skills 沙箱:`docker` / `local` / `disabled` |
|
||||
| `WEKNORA_SANDBOX_TIMEOUT` / `WEKNORA_SANDBOX_DOCKER_IMAGE` | 60 / wechatopenai/weknora-sandbox:latest | 沙箱执行超时与镜像 |
|
||||
| Sandbox 配置 | 设置页按空间维护 | 后端、凭据、模板、超时和私网访问策略不再读取 `WEKNORA_SANDBOX_*` |
|
||||
| `WEKNORA_SKILLS_DIR` | 空(镜像内 /app/skills/preloaded) | 自定义 Skills 目录 |
|
||||
| `WEKNORA_AGENT_LLM_TIMEOUT` | 120s | Agent 单次 LLM 调用超时(Go duration 或纯数字秒) |
|
||||
| `WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT` / `_FAIL_OPEN` | 600s / fail-close | MCP 工具人工审批等待与失败策略 |
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ WeKnora 采用"主服务 + 前端 + 文档解析微服务"的三进程核心架
|
|||
| `docreader` | `wechatopenai/weknora-docreader`(`docker/Dockerfile.docreader`,Python) | `50051`(仅 compose 网络内 expose,不映射宿主机) | 文档解析微服务:gRPC 服务端,PDF/DOCX/Excel/EPUB/网页等 25+ 格式解析与页面渲染。健康检查 `grpc_health_probe` |
|
||||
| `postgres` | `paradedb/paradedb:v0.22.2-pg17` | `5432`(网络内) | 主数据库。ParadeDB 发行版自带 BM25 全文检索与 pgvector 向量能力,因此**默认部署无需独立向量库**(`RETRIEVE_DRIVER=postgres`) |
|
||||
| `redis` | `redis:7.0-alpine`(`appendonly` + `requirepass`) | `6379`(网络内) | Asynq 任务队列、SSE 流管理(跨实例)、system_settings 发布订阅、限流与分布式模型并发闸门 |
|
||||
| `sandbox` | `wechatopenai/weknora-sandbox`(`docker/Dockerfile.sandbox`) | — | 非常驻服务,仅用于 build/pull 镜像;`app` 执行 Agent Skills 时按需 `docker run` 该镜像(`WEKNORA_SANDBOX_MODE=docker`),用毕即释 |
|
||||
| `sandbox` | `wechatopenai/weknora-sandbox`(`docker/Dockerfile.sandbox`) | — | WeKnora 标准运行镜像;可直接用于空间 Docker 后端,接入 CubeSandbox/E2B 时则通过模板 API 自动注册并用于 Agent Skills |
|
||||
|
||||
`app` 与 `docreader` 之间还通过共享卷 `docreader-tmp`(挂载于 `/tmp/docreader`)传递解析产物图片;`app` 的本地文件存储卷为 `data-files`(`/data/files`)。
|
||||
|
||||
|
|
|
|||
|
|
@ -402,19 +402,13 @@ description: Extract text and tables from PDF files, fill forms, merge documents
|
|||
|
||||
Agent 侧的启停在 `configureSkillsFromAgent`(`internal/application/service/session_agent_qa.go`):
|
||||
|
||||
- **沙箱关闭(`WEKNORA_SANDBOX_MODE` 为空或 `disabled`)时技能整体不可用**;
|
||||
- 智能体未选择空间级沙箱配置时,脚本执行工具不可用,但仍可浏览技能说明;
|
||||
- `SkillsSelectionMode`:`all` = 全部预置技能、`selected` = `SelectedSkills` 白名单、`none`/空 = 禁用;
|
||||
- 用户 `@技能` 提及会经 `applyPerRequestSkillScope` 把本轮白名单收窄到提及集合,并作为 `PinnedSkillInfo` 注入 `<must_use>` 块("Must call read_skill(...) before answering")。
|
||||
|
||||
### 5.3 与沙箱(internal/sandbox)的关系
|
||||
|
||||
`execute_skill_script` → `skills.Manager.ExecuteScript` → `sandbox.Manager.Execute`。沙箱由环境变量配置:
|
||||
|
||||
| 环境变量 | 含义 | 默认 |
|
||||
| --- | --- | --- |
|
||||
| `WEKNORA_SANDBOX_MODE` | `docker` / `local` / `disabled` | `disabled` |
|
||||
| `WEKNORA_SANDBOX_DOCKER_IMAGE` | Docker 沙箱镜像 | `wechatopenai/weknora-sandbox:latest` |
|
||||
| `WEKNORA_SANDBOX_TIMEOUT` | 执行超时(秒) | 60 |
|
||||
`execute_skill_script` → `skills.Manager.ExecuteScript` → `sandbox.Manager.Execute`。Docker、Local、CubeSandbox、E2B 均通过「设置 → 沙箱后端」的同一套空间配置与检查接口维护;远端模板从目标 Cube/E2B 集群实时拉取,缺少 WeKnora 标准模板时自动创建。Docker/Local 每次独立执行,不写入会话沙箱绑定。
|
||||
|
||||
**Manager 与校验器**(`internal/sandbox/manager.go`、`validator.go`):每次执行前,除非 `SkipValidation`,`ScriptValidator` 会做四类静态校验,任一命中即拒绝执行并返回 `ErrSecurityViolation`:
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue