feat(sandbox) (#2301)

* cubesandbox support

* feat(agent): add sandbox shell execution, file management tools, and Artifacts collection/download system

- Add three sandbox agent tools: shell_exec / sandbox_ls / sandbox_read
  - shell_exec: safely execute shell commands in session sandbox with timeout & output truncation
  - sandbox_ls: enumerate files under sandbox artifact output directory with recursive listing & pagination
  - sandbox_read: read sandbox file content with offset-based chunked reading
- Add Artifacts system:
  - ArtifactCollector: real-time collection of sandbox tool output files, attached to messages
  - /api/artifacts/{session_id}/{message_id}/{filename}: download endpoint for frontend
  - ChatArtifactsDrawer.vue: frontend artifacts sidebar UI
  - DB migration 000066_message_artifacts: add artifacts column to messages table
- Attachment sandbox staging: upload user attachments to session sandbox on QA request for skill tool access
- Update Agent Prompts: add shell/sandbox tool usage constraints and safety rules
- Extend Agent Observe: include agent steps in Langfuse observability tracing
- Refactor Sandbox SessionManager: support session-scoped file listing, reading, and status queries
- Frontend: render artifact events in AgentStreamDisplay, i18n updates for 4 locales
- Add comprehensive tests: shell_exec_test, sandbox_read_test, artifact_collector_test, etc.

* feat(agent):add remote sandbox client abstract  & client errors

* feat(sandbox): implement Redis binding store with distributed lifecycle lock;

* feat(sandbox): add remote session lifecycle with ownership context

Implement remoteSessionLifecycle to coordinate persistent remote sandboxes
across multi-instance deployments. Supports Resolve (lazy provision,
recovery, race-safe create) and Destroy with compare-delete semantics.
Add ownership context isolation to decouple remote resource cleanup from
request cancellation.

* feat(sandbox): add CubeRemoteClient adapter for RemoteSandboxClient

Implement CubeRemoteClient as a provider-neutral RemoteSandboxClient
implementation. Error normalization, timeout mapping, and metadata
support are fully integrated. SDK details remain private to the
adapter.

* refactor(sandbox): decouple SessionBoundManager from Cube

Remove internal/sandbox/cube.go (CubeSandbox, sync.Map reaper). Add
RemoteSandbox as provider-neutral Sandbox interface implementation.
Rewrite SessionBoundManager to depend on RemoteSandboxClient +
SessionSandboxBindingStore + SessionExistenceChecker, with all
lifecycle ops delegated to remoteSessionLifecycle (Redis + distributed
lock). Application-layer interfaces migrated to RemoteDirEntry/StatEntry
with time.Time ModTime. Cleanup delegated to provider idle-timeout.

* refactor(agent): enhance session capability handling in sandbox manager

- Introduced sessionFileStore and sessionShellExecutor functions to centralize capability checks for session-scoped file and shell execution.
- Updated agent service to register tools based on the presence of session filesystem capabilities, improving compatibility with various sandbox backends.
- Refactored tests to validate behavior when session capabilities are absent, ensuring robust handling of different sandbox types.
- Removed Cube-specific checks, promoting a more provider-neutral approach to session management.

* refactor(sandbox): add E2B backend, modernize Cube adapter, and enable multi-instance Redis binding

- Add e2b_remote_client.go (~850 lines) — full RemoteSandboxClient implementation
  covering lifecycle, execution, and filesystem ops (ListDir/Stat/MakeDir/Remove)
- Wire E2B into NewManagerFromType and container/bootstrap path (buildE2BManager)
- Dependency: matiasinsaurralde/go-e2b v0.1.0

- Cut ~1500 lines of legacy SDK wrapper (cube_client.go, cube_envd.go,
  cube_defaults.go) and replace with direct *cubesandbox.Client usage
- Parse CubeProxy URL directly in adapter (parseProxyURL), removing the
  old hand-rolled envd transport layer
- Pass lifecycle extra fields (onTimeout, autoResume) via SDK CreateOptions.Extra
- Target Cube deployment v0.5.1

- Add RemoteNetworkPolicy to RemoteCreateRequest with AllowInternetAccess,
  AllowPublicTraffic, AllowOut/DenyOut — shared by Cube and E2B adapters
- Both adapters default to permissive (internet+public on) for backwards compat

- Add selectSessionBindingStore() — Redis-backed or in-memory, controlled by
  WEKNORA_SANDBOX_REDIS_NAMESPACE / WEKNORA_REDIS_NAMESPACE
- Add repositorySessionExistenceChecker — checks session existence via DB
  (gorm.ErrRecordNotFound → not exists, transient errors → preserve binding)
- newSandboxManager() now accepts redisClient + sessionRepo; deprecated
  hardcoded NewMemorySessionSandboxBindingStore() in production path

- buildSessionCreateRequest default timeout action: Kill → Pause+AutoResume
  (Cube and E2B). Sessions survive brief idle periods; providers still
  handle TTL-based reaping.

- buildSessionCreateRequest() and effectiveHTTPTimeout() parameterized
  by RemoteProvider (was hardcoded to Cube Config fields)
- NewSessionBoundManager validates provider and delegates defaults to
  per-provider apply*Defaults helpers

- Legacy SDK wrapper: cube_client.go, cube_envd.go, cube_defaults.go,
  cube_envd_test.go, cube_net_diag_test.go, cube_test.go (~2500 lines)
- Unused helpers: DefaultManager.validateExecution, IsRemoteTerminal,
  IsRemoteUnsupported, IsRemoteTransient, ShouldPreserveRemoteBinding
- Dead Config fields: CubeEnvdPort, CubeIdleTTL, AllowedCmds
- Dead ExecuteResult method: GetOutput
- Unused test: session_artifacts_integration_test.go
- Preloaded skill: sandbox-test-python

- Extract shared httpErrorKind() from per-adapter normalize functions
- Add SupportsFilesystemEnumeration capability flag — gates SessionFileStore
  advertisement (E2B returns true post-reconnect, Cube always true)
- Fix stale comments: Cube-only → remote backends, remove "tomorrow"/"future"
- Bump session sandbox TTL defaults: 604800s → 300s (.env.example)
- Update docs/agent-skills.md: full multi-instance deployment guide

Total: 29 files, +1188 / -3721

* feat(agent): bind collected skill artifacts to owning message in resource registry

When ArtifactCollector persists a skill-generated file it now registers a
resource:// binding (owner_type=message, owner_id=assistantMessageID,
relation=artifact) in addition to the messages.artifacts JSONB record. This
mirrors how knowledge uploads and chat attachments bind their resources, so
artifacts can be enumerated and garbage-collected through the resource
registry instead of only via the message JSONB column.

- ArtifactCollector: inject ResourceCatalog, add messageID to Collect/
  maybePersist, and add best-effort bindArtifactResource (binding failures are
  logged, never drop the artifact; only resource:// refs are bound).
- agent_stream_handler: pass assistantMessageID into Collect.
- Renumber message_artifacts migration 000066 -> 000077 to resolve the
  version collision with existing migrations (upstream now uses 000075/000076).
- Tests: update collector signatures and add coverage for the binding path
  and for graceful degradation when Bind fails.

Note: binding applies to newly generated artifacts only; existing rows are
not backfilled.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(sandbox): harden remote sandbox security and artifact collection

Disable Cube local fallback so skill scripts never run on the host when
the remote provider is unavailable. Require Redis for cube/e2b binding
unless WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true for single-node dev.

Collect artifacts with WithoutCancel so user stop does not drop files,
reject shell_exec work_dir outside /workspace, and refuse session-scoped
Execute when a local fallback would be engaged.

* fix(ci): gofmt sandbox files and resolve artifact drawer type error

Apply gofmt to PR-touched Go files and narrow ChatArtifactsDrawer
props in AgentStreamDisplay so session-id is always a string.

* fix(sandbox): adapt to upstream main after rebase

Renumber the message_artifacts migration 000077 -> 000079: upstream now
uses 000077_remove_wiki_log and 000078_chunk_editing_and_custom_metadata.

Declare empty model-handle policies for shell_exec / list_sandbox_files /
read_sandbox_file. Upstream added a coverage test requiring every
UI-exposed tool to declare one; sandbox output is arbitrary skill-authored
content, so it gets the same treatment as execute_skill_script.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(sandbox): replace single tenant sandbox config column with a configs table to support multi-sandbox config per tenant.

* feat(sandbox): add sandbox config entity, cordon lease and session pin field

* feat(sandbox): add sandbox config repository with tenant scoping and cordon lease

* feat(sandbox): stamp sandbox config ID onto sandbox metadata

* feat(sandbox): scope sandbox listing, release and reaping to a single config

* feat(sandbox): resolve managers per config and refuse cordoned or missing configs

* feat(sandbox): implement session pinning and config identity change detection

- Add SessionSandboxPinner with read/pin/clear to bind session to config
- Refactor four entry points (execute/attachment/artifact/destroy) to use pinned config
- Add config_identity.go to detect identity changes by effective values (APIURL/APIKey/Domain/ProxyURL)
- Add SandboxIdentityChanged with key-masked comparison to prevent false 409 conflicts
- Fix artifact collection for default backend and destroy for legacy empty-pin sessions

* feat(sandbox): add multi-tenant sandbox config management and HTTP APIs

Service layer:
- Add sandbox config business service supporting CRUD and inventory listing
- For non-identity changes (e.g., template, TTL), save directly without locking or remote interactions
- For identity changes (e.g., API key, endpoint), reject save if there are still live sandboxes under this config on the remote side,
  and return structured inventory details (sandbox count, affected sessions, related agents) for frontend prompting
- Before deleting a config, check remote live sandboxes; if occupied, reject and prompt user to end sessions or create a new config
- Identity comparison based on effective values to avoid normal saves being misidentified as credential rotation

HTTP interfaces and routing:
- Add REST endpoints for sandbox config (List/Create/Get/Update/Delete/Inventory)
- Mask sensitive credentials (API key, etc.) in all read responses
- Return 409 with structured inventory details on rejection scenarios
- sandbox-check probing supports specifying an existing config_id directly
- Remove old handler file, consolidate validation logic into service layer
- DI wiring and route registration for all six endpoints

* feat(sandbox): add sandbox_config_id field to allow agent referencing named sandbox config

- Add SandboxConfigID field to CustomAgentConfig with omitempty; empty value falls back to global defaults
- Validate config existence on create/update; return 400 if not found
- Inject sandboxConfigService into CustomAgentHandler
- Add unit tests covering field serialization and validation logic

* feat(sandbox, agent): Migrate sandbox config to multi-config CRUD, support named backend selection and workspace scripts policy

Migrate frontend API from legacy KV single-config to /sandbox-configs REST interface, supplement type definitions, detection methods and policy fields; refactor sandbox settings page to multi-config card grid, manage configs with cube/e2b tabs, add editor drawer for create/edit/delete, connection testing and occupancy hints, and add workspace scripts policy toggle; add sandbox config dropdown in Agent editor skill section, integrate config caching, and support selecting named config or falling back to deployment default.

* feat(sandbox): Unify sandbox disable semantics and add tenant-level policy master switch

- Backend: Unify interception in resolveTenantSandboxForConfig with priority: global disable > tenant disable > default fallback > named config; add deploymentSandboxDisabled() using env var to avoid mis‑impacting named E2B; update WorkspaceSandboxPolicy comment as master switch for entire workspace; add unit tests for various scenarios.
- Frontend: Sync i18n copy: button text changed to "Disable/Enable sandbox execution"; confirmation dialog clarifies impact scope; success/failure messages aligned.
- Semantic layering: WEKNORA_SANDBOX_MODE=disabled disables globally; tenant‑level "Disable sandbox execution" only disables for the current workspace.

* feat(sandbox): Add SSRF protection, Agent binding to named configs, and reference query capabilities

- Add outbound URL security guard to validate Cube/E2B API/Proxy addresses against SSRF (including cloud metadata), support allowing private endpoints via env var, link-local always blocked
- Add named backend type validation, only cube/e2b can be stored as workspace named config
- Add sandbox config ID field to Agent at runtime, resolve sandbox for attachments and execution based on Agent's selected named config instead of always global default
- Add query to list Agents referencing a sandbox config ID, useful for deletion/changes to show dependents
- Adapt artifact collector and other callers to fill missing resolve signature parameter

* fix(sandbox): fix session teardown and config-update, add HTTP pool sharing for Cube

Session teardown & deletion ordering
- Move sandbox destroy (and pin `Clear`) before soft‑delete operations (`DeleteSession`/`BatchDeleteSessions`/`DeleteAllSessions`) to prevent remote sandbox leaks and stale pins.
- Pass deployment‑wide `SessionBoundManager` as fallback into `resolveTenantSandboxForConfig` for sentinel pins (`"-"`) to support deployment‑default sessions.

## Config update edge cases
- When identity fields change but old credentials cannot build a client or list config sandboxes, log a warning and proceed with the update instead of returning `sandbox_inventory_unverifiable`; live sandboxes still return 409.
- UI: move `sandboxes_still_live` / `unverifiable` alerts to the top of the sandbox config drawer and auto‑scroll on save refusal and connectivity check results.

Artifact collection for Cube skills
- Pre‑create `/workspace/output` via envd with correct ownership/permissions for `DefaultSandboxExecUser` to ensure Cube skill artifacts are collected properly by `ArtifactCollector`.

HTTP pool sharing for named Cube configs
- Named sandbox configs rebuilt a client on every `Resolve`, causing fresh TCP connections to CubeAPI and the envd proxy on each request.
- Add `CubeTransportPool` and `cubeSplitTransport`:
  - Control plane traffic reuses the same `SharedTransport` as E2B.
  - Data plane traffic uses a guarded transport cached per proxy host:port, preserving the sandbox `Host` header.
- Wire the pool through the tenant resolver `buildClient`; keep SDK defaults for the deployment‑default manager and connectivity probes.

* feat(sandbox): sandbox execution DefaultUser change from root to user

* fix(multi-sandbox-config-per-tenant): align deployment config with tenant resolver and centralize defaults

- Merge form overrides onto DeploymentConfig() via WEKNORA_SANDBOX_* env vars
  instead of DefaultConfig() hardcoded values, allowing empty fields to inherit
  from .env rather than Go constants
- Centralize deployment baseline parsing in sandbox/defaults.go with
  DeploymentConfig, CubeConfigFromEnv, E2BConfigFromEnv
- Delegate container startup to shared helpers to avoid drift
- Propagate tenant env_vars through ResolveEffectiveConfig into
  buildSessionCreateRequest for both Cube and E2B session sandboxes

* fix(multi-sandbox-config-per-tenant): fix some bugs frontend.

* fix(sandbox): guard check-path dials, fix staging gate and shared-agent binding tenant

Three defects found while reviewing the remote sandbox work:

- The Cube connectivity probe and the deployment-default Cube/E2B managers
  built clients without a guarded transport, so an admin-supplied api_url or
  proxy_url could reach link-local addresses via DNS rebinding even though
  save-time validation passed. All three now dial through the same outbound
  guard the per-tenant resolver enforces.

- Attachment staging was gated on the process-wide manager, so a workspace
  pointing an agent at a named Cube/E2B config while the deployment default
  stayed docker/local would run its tools remotely against an empty
  /workspace/input. The gate now resolves the manager the session actually
  runs on.

- Session to sandbox bindings were keyed by the tenant in context, which a
  shared agent deliberately swaps for the agent owner's so models, KBs and
  named configs resolve in the sharing workspace. Session deletion only ever
  knows the session's own tenant, so teardown looked up a key nobody wrote
  and abandoned a paused MicroVM that keeps billing. The binding tenant is
  now carried separately and survives CloneContext.

* chore(sandbox): renumber migrations above upstream and de-collide test stub

Upstream main took 000079 (knowledge_folder_path) and 000080
(knowledge_base_auto_tag_config) while this branch was open, so the three
sandbox migrations move to 000081-000083. golang-migrate requires unique,
ordered versions, and the RAISE NOTICE labels move with the file names.

Main also added a handler test declaring stubSessionService in the same
package; the artifact download test's configurable variant is renamed rather
than merged, since the two stubs answer GetSession differently.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
nullptr-error 2026-08-10 21:28:20 +08:00 committed by GitHub
parent 20c9e5cfe1
commit 5df788dc77
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
161 changed files with 24313 additions and 136 deletions

View File

@ -44,3 +44,6 @@ tmp_dir = "tmp"
clear_on_rebuild = false
keep_scroll = true
[cmd]
# 重启前执行的清理命令
stop = "sudo lsof -t -i :18080 | xargs -r sudo kill -9"

View File

@ -569,12 +569,69 @@ SYSTEM_AES_KEY=weknora-system-aes-key-32bytes!!
# #####################################################################
# ========== G1. Agent Skills Sandbox ==========
# Sandbox 模式:docker(默认)/ local / disabled。
# 以下 WEKNORA_SANDBOX_* 均为「部署级默认值」。工作区可在「设置 → 沙箱后端」中维护
# 多份具名配置(同一后端类型也可以有多份,例如两个 E2B 账号),智能体在编辑弹窗的
# 「能力扩展 → 沙箱后端」里各自选择其一;未选择的智能体回落到这里的默认值。
# 具名配置是自包含的:不会回退到这里的值,端点/密钥/域名/模板必须在配置里填全。
#
# Sandbox 模式:docker(默认)/ local / cube / e2b / disabled。
# docker - Docker 容器隔离(一次性容器)
# local - 本地进程 + 白名单(一次性执行)
# cube - Tencent CubeSandbox MicroVM(会话级持久,每 Session 独占一个沙箱)
# e2b - E2B 云端 MicroVM(会话级持久;依赖第三方 SDK go-e2b)
# disabled - 关闭本实例全部沙箱能力(含工作区具名配置;部署级总闸)
WEKNORA_SANDBOX_MODE=docker
# 脚本执行超时(秒,默认 60)。
WEKNORA_SANDBOX_TIMEOUT=60
# Sandbox Docker 镜像(默认 wechatopenai/weknora-sandbox:latest)。
# WEKNORA_SANDBOX_DOCKER_IMAGE=wechatopenai/weknora-sandbox:latest
# 是否允许租户沙箱配置使用 loopback / 私网地址(127.0.0.1、RFC1918)。
# 自建 Cube/E2B 必填 true;公网 SaaS _endpoint 保持 false(默认)。
# 无论何种取值,169.254.0.0/16(云 metadata)始终禁止。
# WEKNORA_SANDBOX_ALLOW_PRIVATE_ENDPOINTS=false
# ---------- 会话级沙箱通用配置(cube / e2b 生效) ----------
# 工作区使用具名 Cube/E2B 配置,或部署默认 mode=cube/e2b 时,需要 REDIS_ADDR
# 以在多实例间共享 session→sandbox binding。仅单机 dev 可:
# WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true
# 会话→沙箱绑定的 Redis key 命名空间。不设置时复用 WEKNORA_REDIS_NAMESPACE,
# 再退回到 "weknora"。
# WEKNORA_SANDBOX_REDIS_NAMESPACE=weknora
# ---------- CubeSandbox 专用配置(仅当 WEKNORA_SANDBOX_MODE=cube 时生效) ----------
# CubeAPI 端点,用于创建/销毁沙箱。参考 Cube 部署中的 CUBE_API_BIND。
WEKNORA_SANDBOX_CUBE_API_URL=http://127.0.0.1:33000
# CubeProxy 端点,用于通过 Host 头路由到 envd 执行脚本/上传文件。
# 参考 Cube 部署中的 CUBE_PROXY_HTTP_PORT(默认 80)。
WEKNORA_SANDBOX_CUBE_PROXY_URL=http://127.0.0.1:80
# CubeProxy 使用的沙箱路由域名(参考 CUBE_API_SANDBOX_DOMAIN)。
WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN=cube.app
# X-API-Key 认证头;本地部署一般无鉴权,保持为空即可。
# WEKNORA_SANDBOX_CUBE_API_KEY=
# 默认模板 ID(在 CubeMaster 中注册的模板)。
WEKNORA_SANDBOX_CUBE_TEMPLATE=tpl-54becd2c417742e6a190bd3e
# Cube 端沙箱 TTL(秒),到期后 Cube 侧 pause(非销毁)。默认 1800(30 分钟)。
WEKNORA_SANDBOX_CUBE_SANDBOX_TTL=1800
# 单次 HTTP 请求的超时(秒);不影响脚本执行本身的超时。默认 30。
# WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT=30
# ---------- E2B 专用配置(仅当 WEKNORA_SANDBOX_MODE=e2b 时生效) ----------
# 说明:E2B 后端依赖第三方 SDK go-e2b。
# E2B API Key(必填),从 https://e2b.dev/dashboard 获取。
# WEKNORA_SANDBOX_E2B_API_KEY=
# E2B 控制面地址,默认 https://api.e2b.app(自建部署可覆盖)。
# WEKNORA_SANDBOX_E2B_API_URL=https://api.e2b.app
# envd 路由域名,默认 e2b.app(自建部署可覆盖)。
# WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN=e2b.app
# 模板 ID / 别名(在 E2B 上先构建,见 https://e2b.dev/docs/template)。
# WEKNORA_SANDBOX_E2B_TEMPLATE=base
# E2B 端 idle timeout(秒),默认 300;超过后 E2B 自动paused。
# WEKNORA_SANDBOX_E2B_SANDBOX_TTL=300
# 单次 HTTP 请求的超时(秒),默认 30。
# WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT=30
# 自定义 Skills 目录(挂载后指定,免重建镜像)。
# WEKNORA_SKILLS_DIR=
# 智能体大模型调用默认超时(秒,默认 120;复杂推理调大如 300/600)。

View File

@ -316,6 +316,14 @@ services:
- WEKNORA_SANDBOX_MODE=${WEKNORA_SANDBOX_MODE:-docker}
- WEKNORA_SANDBOX_TIMEOUT=${WEKNORA_SANDBOX_TIMEOUT:-60}
- WEKNORA_SANDBOX_DOCKER_IMAGE=${WEKNORA_SANDBOX_DOCKER_IMAGE:-wechatopenai/weknora-sandbox:${WEKNORA_VERSION:-latest}}
- WEKNORA_SANDBOX_REDIS_NAMESPACE=${WEKNORA_SANDBOX_REDIS_NAMESPACE:-}
# E2B (experimental; leave empty unless WEKNORA_SANDBOX_MODE=e2b).
- WEKNORA_SANDBOX_E2B_API_KEY=${WEKNORA_SANDBOX_E2B_API_KEY:-}
- WEKNORA_SANDBOX_E2B_API_URL=${WEKNORA_SANDBOX_E2B_API_URL:-}
- WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN=${WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN:-}
- WEKNORA_SANDBOX_E2B_TEMPLATE=${WEKNORA_SANDBOX_E2B_TEMPLATE:-}
- WEKNORA_SANDBOX_E2B_SANDBOX_TTL=${WEKNORA_SANDBOX_E2B_SANDBOX_TTL:-}
- WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT=${WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT:-}
# Agent LLM call timeout
- WEKNORA_AGENT_LLM_TIMEOUT=${WEKNORA_AGENT_LLM_TIMEOUT:-}
- WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT=${WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT:-}

View File

@ -124,21 +124,74 @@ type AgentConfig struct {
### Sandbox 配置(环境变量)
Sandbox 相关配置通过环境变量设置:
下表的环境变量是**部署级默认值**。工作区还可以维护多份具名沙箱后端配置,智能体各自选用其一;未选择的智能体回落到这里的默认值(见「工作区沙箱后端配置」)。
| 环境变量 | 说明 | 默认值 |
|---------|------|--------|
| `WEKNORA_SANDBOX_MODE` | sandbox 模式: `docker`, `local`, `disabled` | `disabled` |
| `WEKNORA_SANDBOX_MODE` | sandbox 模式:`docker` / `local` / `cube` / `e2b` / `disabled` | `disabled` |
| `WEKNORA_SANDBOX_TIMEOUT` | 脚本执行超时(秒) | `60` |
| `WEKNORA_SANDBOX_DOCKER_IMAGE` | 自定义 Docker 镜像 | `wechatopenai/weknora-sandbox:latest` |
| `WEKNORA_SANDBOX_DOCKER_IMAGE` | 自定义 Docker 镜像(docker 模式) | `wechatopenai/weknora-sandbox:latest` |
| `WEKNORA_SANDBOX_REDIS_NAMESPACE` | 会话→沙箱绑定的 Redis key 命名空间(cube / e2b 生效;未设置时复用 `WEKNORA_REDIS_NAMESPACE`) | `weknora` |
| `WEKNORA_SANDBOX_CUBE_*` | Cube 后端专用配置,见 `.env.example` | — |
| `WEKNORA_SANDBOX_E2B_*` | E2B 后端专用配置,见 `.env.example`(`WEKNORA_SANDBOX_E2B_API_KEY` 必填) | — |
### Sandbox 模式
| 模式 | 说明 |
|------|------|
| `docker` | 使用 Docker 容器隔离(推荐) |
| `local` | 本地进程执行(基础安全限制) |
| `disabled` | 禁用脚本执行 |
| 模式 | 状态 | 说明 |
|------|------|------|
| `docker` | 稳定 | 使用 Docker 容器隔离(推荐用于本地/单机部署) |
| `local` | 基础 | 本地进程执行(仅基础白名单,无 MicroVM 隔离) |
| `cube` | 稳定 | Tencent CubeSandbox MicroVM;会话级持久,支持多机(需 Redis) |
| `e2b` | 稳定 | E2B 云端 MicroVM;会话级持久,支持多机(需 Redis);依赖第三方 SDK go-e2b |
| `disabled` | — | 关闭本实例全部沙箱能力,含工作区具名配置 |
### 工作区沙箱后端配置
一个工作区可以维护**多份具名**沙箱后端配置(「设置 → 沙箱后端」),智能体在编辑弹窗的「能力扩展 → 沙箱后端」里各自选一份。不选就使用上表的部署级默认后端,行为与本特性上线前完全一致。
同一后端类型可以有多份配置:例如两份 E2B 分别指向不同账号或区域,让不同智能体的技能脚本落在不同配额上。
**具名配置是自包含的,不继承 `.env`。** 部署级 `WEKNORA_SANDBOX_*` 只服务「没有选择任何具名配置」的智能体;具名配置里留空的字段不会回退到那些值,必须自己填全:
| 后端 | 必填 | 可留空 |
|---|---|---|
| Cube | API 端点、Proxy 端点、沙箱域名、模板 ID | API Key(自建部署通常无鉴权) |
| E2B | API Key、模板 ID | API 端点、沙箱域名(go-e2b 自行解析默认值) |
留空必填项在保存时就会被拒绝(HTTP 400,报文里列出缺哪些字段),而不是等到第一次执行技能才失败。HTTP 超时与沙箱 TTL 留空走**内置默认值**,同样不看 `.env`。唯一仍沿用部署值的是「执行超时」,因为它属于运维护栏而非后端身份。
这条规则换来的是:库里那一行就是沙箱位置的完整描述。因此身份比较不必再去解析 `.env`,改 `.env` 也不会在无人察觉的情况下把某份配置重新指向别的账号。
**会话与配置的绑定是「随沙箱同生共死」的钉子。** 会话首次创建沙箱时,把当时用的配置 ID 记在 `sessions.sandbox_config_id` 上;此后该会话的附件上传、产物收集、沙箱销毁都锁定在这份配置上。改智能体的选择**只影响之后新建的沙箱**——否则管理员改一次配置,正在进行的会话就会去错误的账号里找产物,销毁也会打空,留下一个没人知道 ID 的 paused 沙箱持续计费。
**有沙箱在跑时改不了身份字段。** 身份字段分两组,成因不同但后果都足够严重:
| 组 | 字段 | 一改会怎样 |
|---|---|---|
| 控制面 | 后端类型、API 端点、API Key | 旧沙箱**再也无法列举/删除/恢复**——新凭据没有权限动它们,而 `onTimeout=pause` 意味着 TTL 也不会回收|
| 数据面 | E2B 沙箱域名;Cube 代理地址、沙箱域名 | 旧沙箱仍可删,但 envd 请求会打到错的主机 ⇒ 该配置下**所有活会话立刻失效**,而沙箱还活着继续计费 |
因此这类修改会被拒绝(HTTP 409),界面会给出沙箱数量、受影响会话数,以及两条出路:**结束或删除那些会话**(删会话会销毁其沙箱),或者**新建一份配置**把智能体指过去(旧凭据原样留着,清理能力不丢)。**没有「释放沙箱」按钮**——那等于在管理员背后销毁正在进行的对话。
**删除配置**只拦远端沙箱,不拦智能体引用:确认弹窗会列出仍指向它的智能体名单,但不阻止删除;删除后那些智能体执行技能时会明确报错,而不是静默换到别的后端。若后端已连不上、无法核实是否仍有沙箱,可以强制删除(这是唯一能强制的情形——能数出来的活沙箱永远不让强删)。
**`sessions.sandbox_config_id` 取值语义:**
| 值 | 含义 |
|---|---|
| `NULL` | 当前无活沙箱(删会话 / 销毁后会 Clear) |
| `"-"` | 活沙箱建在**部署默认**(`.env` `WEKNORA_SANDBOX_*`)上 |
| UUID | 活沙箱建在工作区某份**具名配置**上 |
### 会话级 sandbox 部署要点
- **binding store 自动选择**:无需专门的开关,进程根据 `REDIS_ADDR` 是否配置自动决定绑定存储——配置了 `REDIS_ADDR`(Redis 可用)时使用 Redis binding store,否则退回进程内内存 binding store。命名空间用 `WEKNORA_SANDBOX_REDIS_NAMESPACE`,未设置时依次回退到 `WEKNORA_REDIS_NAMESPACE`、`weknora`。
- **多机部署(生产推荐)**:配置 `REDIS_ADDR`。多副本共享同一 session 的沙箱绑定,通过 Redis SET NX + 可续租分布式锁串行化 create / recover / delete。
- **单机部署**:不配置 `REDIS_ADDR`(或 Lite 模式)时使用进程内内存 binding,仅限单实例。进程重启会丢失 session→sandbox 映射,remote 侧沙箱成为孤儿(注意:**TTL 到期只会暂停、不会销毁**,见下)。
- **切换 provider**:不同 provider 的 sandbox ID 不通用。切换 `WEKNORA_SANDBOX_MODE` 后,旧 session 的 binding 会因 provider 不匹配被 CAS 替换成新 provider 的新沙箱;WeKnora 不做跨 provider 删除。
- **⚠️ 孤儿沙箱不会被 TTL 自动回收**:会话沙箱创建时使用 `onTimeout=pause` + `autoResume=true`(见 `buildSessionCreateRequest`),因此 **TTL 到期是"暂停"而非"销毁"**——保留状态本就是 pause 的目的。加上 CAS 换绑会把旧 sandboxID 从 binding store 覆盖掉,被替换的沙箱会变成**无人知晓 ID 的 paused 孤儿**,持续占用快照存储与费用。删除会话(`session.go` 的 destroyer)与 lifecycle 的惰性 orphan cleanup 都覆盖不到这种情况。生产环境需依赖按 metadata 列举并与 binding 对账的清理任务来回收(`internal/sandbox/orphan_reaper.go`),且**必须显式包含 `paused` 状态**。对账维度是 `(tenant_id, config_id)` 而非仅 `tenant_id`:同一工作区的两份配置可能指向**同一个 provider 账号**(例如同一个 E2B Key 只差模板),只按 `tenant_id` 过滤会把另一份配置的沙箱一并误删。
- **网络策略**:`cube` 与 `e2b` 默认开启公网出口和 public traffic,可在 create 时通过 provider-neutral `RemoteNetworkPolicy`(`AllowInternetAccess` / `AllowPublicTraffic` / `AllowOut` / `DenyOut`)精细化配置;两个 adapter 都实现了同一契约。
## Agent 工具

View File

@ -1,4 +1,4 @@
import { get, post, put, del, postChat } from "../../utils/request";
import { get, post, put, del, postChat, getDown } from "../../utils/request";
@ -80,3 +80,52 @@ export async function stopSession(session_id: string, message_id: string) {
export async function clearSessionMessages(session_id: string) {
return del(`/api/v1/sessions/${session_id}/messages`);
}
// ---------------------------------------------------------------------------
// Skill artifacts (files generated by skill scripts during agent turns)
//
// The backend keeps the storage URL private and indexes each file by its
// position (:index) in the owning assistant message. The list endpoints
// return metadata only — clients must go through downloadArtifact to fetch
// the actual bytes so ownership checks always run server-side.
// ---------------------------------------------------------------------------
export interface ArtifactMeta {
index: number;
file_name: string;
file_type: string;
file_size: number;
source_path: string;
mod_time: string;
created_at: string;
}
// listMessageArtifacts returns the artifacts attached to a single assistant
// message. Used by the drawer opened from the message action toolbar.
export async function listMessageArtifacts(session_id: string, message_id: string) {
return get(
`/api/v1/sessions/${session_id}/messages/${message_id}/artifacts`,
);
}
// listSessionArtifacts returns every artifact recorded against the whole
// session, in creation order. Powers "download everything generated in this
// chat" drawers.
export async function listSessionArtifacts(session_id: string) {
return get(`/api/v1/sessions/${session_id}/artifacts`);
}
// downloadArtifact streams a single artifact's bytes as a Blob so the caller
// can trigger a browser download. A plain `<a href>` cannot be used because
// axios attaches the Bearer token per request; issuing the download via
// `getDown` keeps auth intact and lets the response be turned into an
// object URL.
export async function downloadArtifact(
session_id: string,
message_id: string,
index: number,
): Promise<Blob> {
return getDown(
`/api/v1/sessions/${session_id}/messages/${message_id}/artifacts/${index}/download`,
);
}

View File

@ -669,3 +669,239 @@ export async function purgeArchivedRuntimeTasks(
)
return response as unknown as { success: boolean; deleted: number }
}
// --- Sandbox backend configuration (per workspace) ---
export interface SandboxVolumeMountConfig {
enabled: boolean
mount_path?: string
provider?: string
volume_id?: string
volume_name?: string
volume_owner_fingerprint?: string
}
export interface SandboxCubeConfig {
api_url?: string
proxy_url?: string
sandbox_domain?: string
api_key?: string
template_id?: string
http_timeout_sec?: number
cube_sandbox_ttl_seconds?: number
}
export interface SandboxE2BConfig {
api_url?: string
sandbox_domain?: string
api_key?: string
template_id?: string
http_timeout_sec?: number
e2b_sandbox_ttl_seconds?: number
}
export interface SandboxConfig {
sandbox_type?: string
default_timeout_sec?: number
env_vars?: Record<string, string>
volume_mount?: SandboxVolumeMountConfig
cube?: SandboxCubeConfig
e2b?: SandboxE2BConfig
docker?: { image?: string }
}
/** `ok: null` means the probe was not executed in this run. */
export interface SandboxCheckItem {
name: string
ok: boolean | null
message?: string
latency_ms?: number
}
export interface SandboxCheckResult {
ok: boolean
provider: string
checks: SandboxCheckItem[]
capabilities?: Record<string, boolean>
}
/** Non-secret, inheritable defaults from the deployment's .env configuration. */
export interface SandboxProviderDefaults {
api_url?: string
proxy_url?: string
sandbox_domain?: string
template_id?: string
api_key_configured: boolean
http_timeout_sec?: number
sandbox_ttl_seconds?: number
}
export interface SandboxConfigDefaults {
sandbox_type: string
default_timeout_sec?: number
docker_image?: string
cube?: SandboxProviderDefaults
e2b?: SandboxProviderDefaults
}
/** One named sandbox backend config. Credentials arrive masked. */
export interface SandboxConfigRecord {
id: string
name: string
description?: string
sandbox_type: string
config: SandboxConfig
created_at: string
updated_at: string
}
/** Create/update payload. */
export interface SandboxConfigUpsert {
name: string
description?: string
config: SandboxConfig
}
/**
* What a config currently holds. `sandbox_count` comes from the provider, so a
* non-zero value is authoritative: identity edits and deletion are refused
* until it reaches zero.
*
* `unverifiable` means the provider could not be reached, so the count is
* UNKNOWN rather than zero — never render it as "0 sandboxes".
*/
export interface SandboxInventory {
sandbox_count: number
session_ids?: string[]
agent_names?: string[]
unverifiable?: boolean
}
/** Named sandbox backends that support per-config credentials (cube/e2b only). */
export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b'] as const
export function isNamedSandboxBackend(type: string): boolean {
return (NAMED_SANDBOX_BACKEND_TYPES as readonly string[]).includes(type)
}
/**
* Returns every config of the workspace plus the deployment defaults an empty
* field inherits. An empty list means "no named config yet", in which case
* agents run on those defaults — which is NOT the same as disabled.
*/
export function listSandboxConfigs(): Promise<{
data: SandboxConfigRecord[]
defaults?: SandboxConfigDefaults
workspace_scripts_disabled?: boolean
}> {
return get('/api/v1/sandbox-configs') as unknown as Promise<{
data: SandboxConfigRecord[]
defaults?: SandboxConfigDefaults
workspace_scripts_disabled?: boolean
}>
}
export function setSandboxWorkspacePolicy(scriptsDisabled: boolean): Promise<{
workspace_scripts_disabled: boolean
}> {
return put('/api/v1/sandbox-configs/workspace-policy', {
scripts_disabled: scriptsDisabled,
}) as unknown as Promise<{ workspace_scripts_disabled: boolean }>
}
export function createSandboxConfig(
payload: SandboxConfigUpsert,
): Promise<{ data: SandboxConfigRecord }> {
return post('/api/v1/sandbox-configs', payload) as unknown as Promise<{
data: SandboxConfigRecord
}>
}
export function getSandboxConfigById(id: string): Promise<{ data: SandboxConfigRecord }> {
return get(`/api/v1/sandbox-configs/${id}`) as unknown as Promise<{
data: SandboxConfigRecord
}>
}
export function updateSandboxConfigById(
id: string,
payload: SandboxConfigUpsert,
): Promise<{ data: SandboxConfigRecord }> {
return put(`/api/v1/sandbox-configs/${id}`, payload) as unknown as Promise<{
data: SandboxConfigRecord
}>
}
/**
* `force` only overrides an inventory the backend could not verify; it never
* overrides sandboxes the backend can actually see. Ask for it exclusively in
* response to a `sandbox_inventory_unverifiable` conflict.
*/
export function deleteSandboxConfig(id: string, force = false): Promise<void> {
const query = force ? '?force=true' : ''
return del(`/api/v1/sandbox-configs/${id}${query}`) as unknown as Promise<void>
}
export function getSandboxConfigInventory(id: string): Promise<{ data: SandboxInventory }> {
return get(`/api/v1/sandbox-configs/${id}/sandboxes`) as unknown as Promise<{
data: SandboxInventory
}>
}
/**
* Probe a sandbox configuration without saving it. Redacted secrets are
* resolved server-side, so pass `config_id` alongside an edited `config` to
* test unsaved changes without retyping an API key. Omit `config` to probe a
* stored config as-is.
*
* `deep` additionally creates and destroys one sandbox, which is the only way
* to validate the template ID, Cube's proxy data plane and outbound egress.
* It consumes real sandbox time.
*/
export function checkSandboxConfig(payload: {
config?: SandboxConfig
config_id?: string
deep?: boolean
}): Promise<{ data: SandboxCheckResult }> {
return post('/api/v1/system/sandbox-check', payload) as unknown as Promise<{
data: SandboxCheckResult
}>
}
/**
* The two refusals a save or a delete can hit. They mean opposite things:
* `sandboxes_still_live` says the backend counted live sandboxes, so the only
* ways forward are ending the owning sessions or creating a second config;
* `sandbox_inventory_unverifiable` says the backend is unreachable, so nothing
* could be counted — the one case a force delete may override.
*/
export type SandboxConflictCode = 'sandboxes_still_live' | 'sandbox_inventory_unverifiable'
export interface SandboxConflict {
code: SandboxConflictCode
message?: string
/** Present for `sandboxes_still_live`; there is nothing to report otherwise. */
inventory?: SandboxInventory
}
/**
* Reads a sandbox-config conflict out of a rejected request, or returns null
* when the failure is anything else.
*
* The interceptor spreads the response body onto the rejection, so the code
* sits at `err.error.code`. Parsing it in one place keeps callers from
* hard-coding that shape — and from confusing the two conflicts, which drive
* different recovery paths in the UI.
*/
export function parseSandboxConflict(err: unknown): SandboxConflict | null {
if (typeof err !== 'object' || err === null) return null
const detail = (err as { error?: { code?: string; message?: string; data?: SandboxInventory } }).error
if (!detail || typeof detail !== 'object') return null
if (
detail.code !== 'sandboxes_still_live' &&
detail.code !== 'sandbox_inventory_unverifiable'
) {
return null
}
return { code: detail.code, message: detail.message, inventory: detail.data }
}

View File

@ -0,0 +1,506 @@
<template>
<t-drawer
:visible="visible"
:header="record ? $t('settings.sandbox.editTitle') : $t('settings.sandbox.createTitle')"
size="620px"
:confirm-btn="{ content: $t('common.save'), loading: saving }"
:cancel-btn="{ content: $t('common.cancel') }"
@confirm="save"
@close="close"
@update:visible="(v: boolean) => emit('update:visible', v)"
>
<!--
Identity-change refusals must sit at the top: the form is long and the
admin otherwise saves, sees nothing, and assumes the click did nothing.
-->
<div v-if="conflict" ref="conflictAlertRef" class="blocked blocked-top">
<t-alert v-if="conflict.code === 'sandboxes_still_live'" theme="warning"
:message="$t('settings.sandbox.sandboxesStillLive', { count: conflict.inventory?.sandbox_count ?? 0 })">
<template #description>
<p v-if="affectedSessionCount">{{ $t('settings.sandbox.affectedSessions', { count: affectedSessionCount }) }}</p>
<p v-if="conflict.inventory?.agent_names?.length">
{{ $t('settings.sandbox.affectedAgents', { names: conflict.inventory.agent_names.join('、') }) }}
</p>
<p>{{ $t('settings.sandbox.blockedHint') }}</p>
</template>
</t-alert>
<t-alert v-else theme="warning" :message="$t('settings.sandbox.unverifiableBlocked')">
<template #description>
<p>{{ $t('settings.sandbox.unverifiableSaveHint') }}</p>
</template>
</t-alert>
</div>
<t-form label-align="top">
<t-form-item :label="$t('settings.sandbox.configName')" :status="nameError ? 'error' : undefined"
:tips="nameError || undefined">
<t-input v-model="name" :placeholder="$t('settings.sandbox.configNamePlaceholder')" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.configDescription')">
<t-input v-model="description" :placeholder="$t('settings.sandbox.configDescriptionPlaceholder')" />
</t-form-item>
<!--
Only while editing: a config being created owns no sandboxes yet, so
warning that these fields are locked would describe a restriction that
does not apply.
-->
<t-alert v-if="record" theme="info" class="identity-hint"
:message="$t('settings.sandbox.identityFieldHint')" />
<t-form-item :label="$t('settings.sandbox.backend')">
<t-select v-model="backend" @change="onBackendChange">
<t-option v-for="opt in backendOptions" :key="opt" :value="opt" :label="backendLabel(opt)" />
</t-select>
</t-form-item>
<!--
Placeholders are format examples, never the deployment's own values: a
named config inherits nothing, so showing what .env holds would suggest
an empty field still works.
-->
<!-- Cube -->
<template v-if="backend === 'cube'">
<t-form-item :label="requiredLabel('apiUrl')" :status="fieldStatus('api_url')" :tips="fieldTip('api_url')">
<t-input v-model="cube.api_url" placeholder="http://cube.example.com:33000"
@input="onFieldInput('api_url')" />
</t-form-item>
<t-form-item :label="requiredLabel('proxyUrl')" :status="fieldStatus('proxy_url')"
:tips="fieldTip('proxy_url')">
<t-input v-model="cube.proxy_url" placeholder="http://cube.example.com:80"
@input="onFieldInput('proxy_url')" />
</t-form-item>
<t-form-item :label="requiredLabel('sandboxDomain')" :status="fieldStatus('sandbox_domain')"
:tips="fieldTip('sandbox_domain')">
<t-input v-model="cube.sandbox_domain" placeholder="cube.app" @input="onFieldInput('sandbox_domain')" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.apiKey')" :help="$t('settings.sandbox.cubeApiKeyOptional')">
<t-input v-model="cube.api_key" type="password" :placeholder="secretPlaceholder" />
</t-form-item>
<t-form-item :label="requiredLabel('templateId')" :status="fieldStatus('template_id')"
:tips="fieldTip('template_id')">
<t-input v-model="cube.template_id" placeholder="tpl-xxxxxxxx" @input="onFieldInput('template_id')" />
</t-form-item>
<div class="timeout-row">
<t-form-item :label="$t('settings.sandbox.httpTimeout')">
<t-input-number v-model="cube.http_timeout_sec" :min="0" theme="column" placeholder="30" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.sandboxTtl')">
<t-input-number v-model="cube.cube_sandbox_ttl_seconds" :min="0" theme="column" placeholder="1800" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.defaultTimeout')">
<t-input-number v-model="defaultTimeoutSec" :min="0" theme="column"
:placeholder="String(defaults?.default_timeout_sec || 60)" />
</t-form-item>
</div>
</template>
<!-- E2B -->
<template v-else-if="backend === 'e2b'">
<t-form-item :label="$t('settings.sandbox.apiUrl')" :help="$t('settings.sandbox.e2bApiUrlOptional')">
<t-input v-model="e2b.api_url" placeholder="https://api.e2b.app" @input="invalidateCheck" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.sandboxDomain')" :help="$t('settings.sandbox.e2bDomainOptional')">
<t-input v-model="e2b.sandbox_domain" placeholder="e2b.app" />
</t-form-item>
<t-form-item :label="requiredLabel('apiKey')" :status="fieldStatus('api_key')" :tips="fieldTip('api_key')">
<t-input v-model="e2b.api_key" type="password" :placeholder="secretPlaceholder"
@input="onFieldInput('api_key')" />
</t-form-item>
<t-form-item :label="requiredLabel('templateId')" :status="fieldStatus('template_id')"
:tips="fieldTip('template_id')">
<t-input v-model="e2b.template_id" placeholder="xxxxxxxxxxxxxxxx"
@input="onFieldInput('template_id')" />
</t-form-item>
<div class="timeout-row">
<t-form-item :label="$t('settings.sandbox.httpTimeout')">
<t-input-number v-model="e2b.http_timeout_sec" :min="0" theme="column" placeholder="30" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.sandboxTtl')">
<t-input-number v-model="e2b.e2b_sandbox_ttl_seconds" :min="0" theme="column" placeholder="300" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.defaultTimeout')">
<t-input-number v-model="defaultTimeoutSec" :min="0" theme="column"
:placeholder="String(defaults?.default_timeout_sec || 60)" />
</t-form-item>
</div>
</template>
<!-- Environment variables: a map on the wire, editable rows in the UI. -->
<t-form-item :label="$t('settings.sandbox.envVars')"
:help="$t('settings.sandbox.envVarsHint')">
<div class="env-rows">
<div v-for="(row, index) in envRows" :key="index" class="env-row">
<t-input v-model="row.key" :placeholder="$t('settings.sandbox.envKey')" style="width: 200px" />
<t-input v-model="row.value" type="password" :placeholder="$t('settings.sandbox.envValue')"
style="width: 220px" />
<t-button variant="text" theme="danger" @click="envRows.splice(index, 1)">
{{ $t('settings.sandbox.removeRow') }}
</t-button>
</div>
<t-button variant="outline" size="small" @click="envRows.push({ key: '', value: '' })">
{{ $t('settings.sandbox.addRow') }}
</t-button>
</div>
</t-form-item>
</t-form>
<div v-if="isRemoteBackend" class="check-actions">
<t-button variant="outline" :loading="checking" @click="runCheck(false)">
{{ $t('settings.sandbox.testConnection') }}
</t-button>
<t-popconfirm :content="$t('settings.sandbox.deepCheckConfirm')" @confirm="runCheck(true)">
<t-button variant="outline" :loading="checking">
{{ $t('settings.sandbox.deepCheck') }}
</t-button>
</t-popconfirm>
</div>
<div v-if="checkResult" ref="checkResultRef" class="check-result">
<t-alert :theme="checkResult.ok ? 'success' : 'error'"
:message="checkResult.ok ? $t('settings.sandbox.checkPassed') : $t('settings.sandbox.checkFailed')" />
<ul class="check-list">
<li v-for="item in checkResult.checks" :key="item.name" class="check-item">
<t-icon :name="item.ok === true ? 'check-circle-filled'
: item.ok === false ? 'close-circle-filled' : 'minus-circle'"
:class="item.ok === true ? 'ok' : item.ok === false ? 'err' : 'skip'" />
<span class="check-name">{{ checkLabel(item.name) }}</span>
<span v-if="item.latency_ms" class="check-latency">{{ item.latency_ms }} ms</span>
<span v-if="item.message" class="check-message">{{ item.message }}</span>
</li>
</ul>
<t-alert v-if="checkResult.capabilities && checkResult.capabilities.supports_volumes === false" theme="warning"
:message="$t('settings.sandbox.noVolumeSupport')" />
</div>
</t-drawer>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import {
checkSandboxConfig,
createSandboxConfig,
parseSandboxConflict,
updateSandboxConfigById,
type SandboxCheckResult,
type SandboxConfig,
type SandboxConfigDefaults,
type SandboxConfigRecord,
type SandboxConflict,
type SandboxCubeConfig,
type SandboxE2BConfig,
isNamedSandboxBackend,
NAMED_SANDBOX_BACKEND_TYPES,
} from '@/api/system'
const props = defineProps<{
visible: boolean
record: SandboxConfigRecord | null
presetType?: string
defaults: SandboxConfigDefaults | null
}>()
const emit = defineEmits<{
(e: 'update:visible', value: boolean): void
(e: 'saved'): void
}>()
const { t } = useI18n()
// The backend echoes secrets as this placeholder; submitting it unchanged keeps
// the stored value, so the form never needs the real key.
const secretPlaceholder = '***'
const backendOptions = [...NAMED_SANDBOX_BACKEND_TYPES]
const saving = ref(false)
const checking = ref(false)
const checkResult = ref<SandboxCheckResult | null>(null)
const conflict = ref<SandboxConflict | null>(null)
const conflictAlertRef = ref<HTMLElement | null>(null)
const checkResultRef = ref<HTMLElement | null>(null)
const nameError = ref('')
const name = ref('')
const description = ref('')
const backend = ref('')
// undefined rather than 0 so the input renders empty and shows its placeholder,
// matching the HTTP timeout / TTL fields. A literal 0 would read as a real value.
const defaultTimeoutSec = ref<number | undefined>(undefined)
const cube = reactive<SandboxCubeConfig>({})
const e2b = reactive<SandboxE2BConfig>({})
const envRows = ref<{ key: string; value: string }[]>([])
// Only remote backends have a control plane worth probing.
const isRemoteBackend = computed(() => backend.value === 'cube' || backend.value === 'e2b')
const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)
const checkLabel = (probe: string) => t(`settings.sandbox.checks.${probe}`, probe)
// Mirrors sandbox.MissingRequiredFields on the server. Duplicated on purpose:
// the server stays the authority, this only spares the admin a round-trip and
// points at the offending input instead of showing one combined message.
const REQUIRED_FIELDS: Record<string, string[]> = {
cube: ['api_url', 'proxy_url', 'sandbox_domain', 'template_id'],
e2b: ['api_key', 'template_id'],
}
const fieldErrors = ref<Record<string, string>>({})
const fieldStatus = (field: string) => (fieldErrors.value[field] ? 'error' : undefined)
const fieldTip = (field: string) => fieldErrors.value[field] || undefined
const requiredLabel = (labelKey: string) => `${t(`settings.sandbox.${labelKey}`)} *`
// Clearing on input rather than re-validating keeps the error from flickering
// back while the admin is still halfway through typing a URL.
function onFieldInput(field: string) {
delete fieldErrors.value[field]
invalidateCheck()
}
function validateRequiredFields(): boolean {
const required = REQUIRED_FIELDS[backend.value] || []
const values = (backend.value === 'cube' ? cube : e2b) as Record<string, unknown>
const errors: Record<string, string> = {}
for (const field of required) {
const value = values[field]
if (typeof value !== 'string' || value.trim() === '') {
errors[field] = t('settings.sandbox.fieldRequired')
}
}
fieldErrors.value = errors
return Object.keys(errors).length === 0
}
const affectedSessionCount = computed(() => conflict.value?.inventory?.session_ids?.length || 0)
function defaultBackendType(): string {
const fromRecord = props.record?.config?.sandbox_type || props.presetType || ''
if (isNamedSandboxBackend(fromRecord)) return fromRecord
const fromDeploy = props.defaults?.sandbox_type || ''
if (isNamedSandboxBackend(fromDeploy)) return fromDeploy
return 'cube'
}
function reset() {
const cfg: SandboxConfig = props.record?.config || {}
name.value = props.record?.name || ''
description.value = props.record?.description || ''
backend.value = isNamedSandboxBackend(cfg.sandbox_type || '')
? cfg.sandbox_type!
: defaultBackendType()
defaultTimeoutSec.value = cfg.default_timeout_sec || undefined
// Replace rather than merge: a reused reactive object would otherwise carry
// the previously edited config's fields into the next one opened.
Object.keys(cube).forEach((key) => delete (cube as Record<string, unknown>)[key])
Object.keys(e2b).forEach((key) => delete (e2b as Record<string, unknown>)[key])
Object.assign(cube, cfg.cube || {})
Object.assign(e2b, cfg.e2b || {})
envRows.value = Object.entries(cfg.env_vars || {}).map(([key, value]) => ({ key, value }))
checkResult.value = null
conflict.value = null
nameError.value = ''
fieldErrors.value = {}
}
watch(() => props.visible, (open) => {
if (open) reset()
})
function collectPayload(): SandboxConfig {
const envVars: Record<string, string> = {}
for (const row of envRows.value) {
const key = row.key.trim()
if (key) envVars[key] = row.value
}
const payload: SandboxConfig = {
sandbox_type: backend.value,
default_timeout_sec: defaultTimeoutSec.value || undefined,
env_vars: envVars,
}
// Send only the selected backend's block so an unused one cannot fail
// validation (e.g. a stale private URL left in the other tab).
if (backend.value === 'cube') payload.cube = { ...cube }
if (backend.value === 'e2b') payload.e2b = { ...e2b }
return payload
}
function close() {
emit('update:visible', false)
}
async function save() {
const trimmed = name.value.trim()
if (!trimmed) {
nameError.value = t('settings.sandbox.configNameRequired')
return
}
nameError.value = ''
if (!validateRequiredFields()) return
saving.value = true
conflict.value = null
try {
const payload = { name: trimmed, description: description.value, config: collectPayload() }
if (props.record) {
await updateSandboxConfigById(props.record.id, payload)
} else {
await createSandboxConfig(payload)
}
MessagePlugin.success(t('common.saveSuccess'))
emit('saved')
close()
} catch (e: any) {
const refusal = parseSandboxConflict(e)
if (refusal) {
// Keep the drawer open with the form intact: the admin has to act
// elsewhere first, and retyping everything afterwards would be cruel.
conflict.value = refusal
await nextTick()
conflictAlertRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
return
}
MessagePlugin.error(e?.message || t('settings.sandbox.saveFailed'))
} finally {
saving.value = false
}
}
async function runCheck(deep: boolean) {
// The probe builds a real client, so an incomplete config would come back as
// a generic client_build failure instead of naming the empty field.
if (!validateRequiredFields()) return
checking.value = true
checkResult.value = null
try {
// config_id lets the backend resolve masked secrets against the stored row,
// so an edited form can be probed without retyping the API key.
const res = await checkSandboxConfig({
config: collectPayload(),
config_id: props.record?.id,
deep,
})
checkResult.value = res?.data || null
if (checkResult.value) {
await nextTick()
checkResultRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.checkFailed'))
} finally {
checking.value = false
}
}
// A result that no longer matches the form is worse than none.
function invalidateCheck() {
checkResult.value = null
}
// The two backends require different fields, so carrying errors across a switch
// would flag inputs the admin can no longer even see.
function onBackendChange() {
fieldErrors.value = {}
invalidateCheck()
}
</script>
<style scoped>
.identity-hint {
margin-bottom: 16px;
}
.timeout-row {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
margin-bottom: 24px;
}
.timeout-row :deep(.t-form__item) {
margin-bottom: 0;
}
.timeout-row :deep(.t-input-number) {
width: 100%;
}
.env-rows {
display: flex;
flex-direction: column;
gap: 8px;
align-items: flex-start;
}
.env-row {
display: flex;
align-items: center;
gap: 8px;
}
.check-actions {
display: flex;
gap: 12px;
margin-top: 4px;
}
.check-result {
margin-top: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.check-list {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 6px;
}
.check-item {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
}
.check-item .ok {
color: var(--td-success-color);
}
.check-item .err {
color: var(--td-error-color);
}
.check-item .skip {
color: var(--td-text-color-placeholder);
}
.check-name {
min-width: 140px;
}
.check-latency,
.check-message {
color: var(--td-text-color-secondary);
}
.blocked {
margin-top: 16px;
}
.blocked-top {
margin-top: 0;
margin-bottom: 16px;
}
.blocked p {
margin: 4px 0 0;
}
</style>

View File

@ -813,6 +813,16 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
onTurnComplete?.(message)
fullContent.value = ''
currentAssistantMessageId.value = ''
// Hydrate skill-generated artifacts as soon as the SSE completion
// event arrives — without this the download button only appears
// after a page refresh (the assistant message row is fetched via
// getMessageList which does include the artifacts JSON column).
// botmsg.vue / AgentStreamDisplay.vue read `message.artifacts`
// reactively to decide whether to render the download button.
const streamedArtifacts = (dataPayload as any)?.artifacts
if (Array.isArray(streamedArtifacts) && streamedArtifacts.length) {
message.artifacts = streamedArtifacts
}
if (message.agentEventStream) {
;(message.agentEventStream as ChatMessage[]).push({
type: 'agent_complete',

View File

@ -17,6 +17,7 @@ export const SETTINGS_SECTION_MIN_ROLE: Record<string, SettingsRoleKey> = {
vectorstore: 'admin',
parser: 'admin',
storage: 'admin',
sandbox: 'admin',
mcp: 'admin',
system: 'viewer',
userprofile: 'viewer',

View File

@ -801,6 +801,13 @@ export default {
think: 'Thinking',
copy: 'Copy',
addToKnowledgeBase: 'Add to Knowledge Base',
artifactDrawer: {
buttonTitle: 'Download files generated in this reply',
title: 'Generated files',
empty: 'No downloadable files were generated this turn.',
download: 'Download',
downloadFailed: 'Download failed, please retry.',
},
updatePlan: 'Update Plan',
webSearchFound: 'Found <strong>{count}</strong> web search result(s)',
toolFallback: 'Tool',
@ -1007,6 +1014,15 @@ export default {
selectSkills: 'Select Skills',
selectSkillsDesc: 'Choose which Skills to enable',
noSkillsAvailable: 'No preloaded Skills available',
sandboxConfig: 'Sandbox backend',
sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
sandboxBackend: 'Sandbox backend',
sandboxBackendDefault: 'Use deployment defaults',
sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',
sandboxBackendMissing: 'Config deleted',
sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',
sandboxInfoTitle: 'Why choose a backend?',
sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',
skillsInfoTitle: 'What are Skills?',
skillsInfoContent: 'Skills are preloaded professional knowledge modules that provide domain-specific instructions, workflows, and tool support for the Agent. When enabled, the Agent will automatically load relevant knowledge when needed.'
},
@ -1037,6 +1053,101 @@ export default {
vectorStoreEngine: 'Vector DB Engine',
parserEngine: 'Parser Engine',
storageEngine: 'Storage Engine',
sandbox: {
title: 'Sandbox Backend',
description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',
loading: 'Loading sandbox configuration...',
loadFailed: 'Failed to load sandbox configuration',
backend: 'Sandbox backend',
backendHint: 'Leave unset to inherit the global default',
addConfig: 'Add sandbox backend',
viewDeployDefaults: 'View deployment defaults',
deployDefaultsTitle: 'Deployment defaults',
deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',
deployDefaultBackend: 'Default backend',
apiKeyConfigured: 'Configured',
apiKeyNotConfigured: 'Not configured',
configName: 'Config name',
configNamePlaceholder: 'e.g. Production E2B',
configNameRequired: 'Please enter a config name',
configDescription: 'Description',
configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',
createTitle: 'Add sandbox backend',
editTitle: 'Edit sandbox backend',
noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
viewSandboxes: 'View sandbox usage',
inventoryTitle: 'Sandbox usage',
inventoryFailed: 'Failed to load sandbox usage',
sandboxCount: 'Sandboxes',
sandboxCountUnknown: 'Unknown (backend unreachable)',
inventoryUnverifiableHint: 'The backend is unreachable, so the sandbox count is unknown — that is not the same as none.',
sandboxesStillLive: 'This config still owns {count} running or paused sandbox(es), so identity fields cannot be changed yet.',
blockedHint: 'End or delete those sessions (deleting a session destroys its sandbox), or create a second config and point the agents at it.',
unverifiableBlocked: 'The backend cannot be reached to verify whether sandboxes remain, so the stored credentials will not be overwritten.',
unverifiableSaveHint: 'Restore connectivity first; if the backend is gone for good, create a second config and point the agents at it.',
affectedSessions: '{count} session(s) affected.',
affectedAgents: 'Agents using this config: {names}',
confirmDelete: 'Delete sandbox backend "{name}"?',
confirmDeleteWithAgents: 'Delete sandbox backend "{name}"? {agents}They will fail on their next skill execution.',
deleteFailed: 'Failed to delete',
deleted: 'Deleted',
forceDeleteTitle: 'Sandbox usage cannot be verified',
forceDeleteConfirm: 'The backend cannot be reached to verify whether sandboxes remain. If it is gone for good you can force-delete this config; if it is only temporarily unreachable, forcing it leaves any remaining sandboxes with nobody to reclaim them. Force delete anyway?',
forceDelete: 'Force delete',
disableScripts: 'Disable sandbox execution',
enableScripts: 'Enable sandbox execution',
disableScriptsConfirm:
'All agents in this workspace — will no longer run skill scripts in a sandbox. They can still read skill content. Existing remote sandboxes are not destroyed automatically; end or delete the related sessions to release them. Continue?',
scriptsDisabled: 'Sandbox execution disabled for this workspace',
scriptsEnabled: 'Sandbox execution restored for this workspace',
policySaveFailed: 'Failed to update sandbox execution policy',
legacyConfig: 'Deprecated',
namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',
fieldRequired: 'Required',
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
e2bDomainOptional: 'Optional — the SDK default is used when empty',
backends: {
disabled: 'Disabled',
local: 'Local process',
docker: 'Docker',
cube: 'CubeSandbox',
e2b: 'E2B',
},
apiUrl: 'API endpoint',
proxyUrl: 'Proxy endpoint',
sandboxDomain: 'Sandbox domain',
apiKey: 'API key',
templateId: 'Template ID',
httpTimeout: 'HTTP timeout (s)',
sandboxTtl: 'Sandbox TTL (s)',
dockerImage: 'Docker image',
defaultTimeout: 'Execution timeout (s)',
envVars: 'Environment variables',
envKey: 'Name',
envValue: 'Value',
envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
addRow: 'Add variable',
removeRow: 'Remove',
save: 'Save',
saved: 'Saved. Applies to new sessions.',
saveFailed: 'Failed to save',
testConnection: 'Test connection',
deepCheck: 'Full verification',
deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',
checkPassed: 'All checks passed',
checkFailed: 'Some checks failed',
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
checks: {
client_build: 'Client construction',
api_url_reachable: 'Endpoint reachability',
credential_valid: 'Credential validity',
template_exists: 'Template existence',
sandbox_exec: 'In-sandbox execution',
egress_available: 'Outbound network',
},
},
mcpService: 'MCP Service',
versionInfo: 'Version Info',
taskQueue: 'Task Queues',

View File

@ -4652,6 +4652,101 @@ export default {
vectorStoreEngine: '벡터 DB 엔진',
parserEngine: '파싱 엔진',
storageEngine: '스토리지 엔진',
sandbox: {
title: 'Sandbox Backend',
description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',
loading: 'Loading sandbox configuration...',
loadFailed: 'Failed to load sandbox configuration',
backend: 'Sandbox backend',
backendHint: 'Leave unset to inherit the global default',
addConfig: 'Add sandbox backend',
viewDeployDefaults: 'View deployment defaults',
deployDefaultsTitle: 'Deployment defaults',
deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',
deployDefaultBackend: 'Default backend',
apiKeyConfigured: 'Configured',
apiKeyNotConfigured: 'Not configured',
configName: 'Config name',
configNamePlaceholder: 'e.g. Production E2B',
configNameRequired: 'Please enter a config name',
configDescription: 'Description',
configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',
createTitle: 'Add sandbox backend',
editTitle: 'Edit sandbox backend',
noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
viewSandboxes: 'View sandbox usage',
inventoryTitle: 'Sandbox usage',
inventoryFailed: 'Failed to load sandbox usage',
sandboxCount: 'Sandboxes',
sandboxCountUnknown: 'Unknown (backend unreachable)',
inventoryUnverifiableHint: 'The backend is unreachable, so the sandbox count is unknown — that is not the same as none.',
sandboxesStillLive: 'This config still owns {count} running or paused sandbox(es), so identity fields cannot be changed yet.',
blockedHint: 'End or delete those sessions (deleting a session destroys its sandbox), or create a second config and point the agents at it.',
unverifiableBlocked: 'The backend cannot be reached to verify whether sandboxes remain, so the stored credentials will not be overwritten.',
unverifiableSaveHint: 'Restore connectivity first; if the backend is gone for good, create a second config and point the agents at it.',
affectedSessions: '{count} session(s) affected.',
affectedAgents: 'Agents using this config: {names}',
confirmDelete: 'Delete sandbox backend "{name}"?',
confirmDeleteWithAgents: 'Delete sandbox backend "{name}"? {agents}They will fail on their next skill execution.',
deleteFailed: 'Failed to delete',
deleted: 'Deleted',
forceDeleteTitle: 'Sandbox usage cannot be verified',
forceDeleteConfirm: 'The backend cannot be reached to verify whether sandboxes remain. If it is gone for good you can force-delete this config; if it is only temporarily unreachable, forcing it leaves any remaining sandboxes with nobody to reclaim them. Force delete anyway?',
forceDelete: 'Force delete',
disableScripts: 'Disable sandbox execution',
enableScripts: 'Enable sandbox execution',
disableScriptsConfirm:
'All agents in this workspace — will no longer run skill scripts in a sandbox. They can still read skill content. Existing remote sandboxes are not destroyed automatically; end or delete the related sessions to release them. Continue?',
scriptsDisabled: 'Sandbox execution disabled for this workspace',
scriptsEnabled: 'Sandbox execution restored for this workspace',
policySaveFailed: 'Failed to update sandbox execution policy',
legacyConfig: 'Deprecated',
namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',
fieldRequired: 'Required',
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
e2bDomainOptional: 'Optional — the SDK default is used when empty',
backends: {
disabled: 'Disabled',
local: 'Local process',
docker: 'Docker',
cube: 'CubeSandbox',
e2b: 'E2B',
},
apiUrl: 'API endpoint',
proxyUrl: 'Proxy endpoint',
sandboxDomain: 'Sandbox domain',
apiKey: 'API key',
templateId: 'Template ID',
httpTimeout: 'HTTP timeout (s)',
sandboxTtl: 'Sandbox TTL (s)',
dockerImage: 'Docker image',
defaultTimeout: 'Execution timeout (s)',
envVars: 'Environment variables',
envKey: 'Name',
envValue: 'Value',
envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
addRow: 'Add variable',
removeRow: 'Remove',
save: 'Save',
saved: 'Saved. Applies to new sessions.',
saveFailed: 'Failed to save',
testConnection: 'Test connection',
deepCheck: 'Full verification',
deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',
checkPassed: 'All checks passed',
checkFailed: 'Some checks failed',
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
checks: {
client_build: 'Client construction',
api_url_reachable: 'Endpoint reachability',
credential_valid: 'Credential validity',
template_exists: 'Template existence',
sandbox_exec: 'In-sandbox execution',
egress_available: 'Outbound network',
},
},
mcpService: 'MCP 서비스',
versionInfo: '버전 정보',
taskQueue: '작업 큐',
@ -4896,6 +4991,13 @@ export default {
think: '사고',
copy: '복사',
addToKnowledgeBase: '지식베이스에 추가',
artifactDrawer: {
buttonTitle: '이 응답에서 생성된 파일 다운로드',
title: '생성된 파일',
empty: '이번 회차에서 다운로드 가능한 파일이 없습니다.',
download: '다운로드',
downloadFailed: '다운로드에 실패했습니다. 다시 시도해 주세요.',
},
updatePlan: '계획 업데이트',
webSearchFound: '<strong>{count}</strong>개의 웹 검색 결과 발견',
toolFallback: '도구',
@ -5039,6 +5141,15 @@ export default {
selectSkills: 'Skills 선택',
selectSkillsDesc: '활성화할 Skills 선택',
noSkillsAvailable: '사전 설치된 Skills가 없습니다',
sandboxConfig: 'Sandbox backend',
sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
sandboxBackend: 'Sandbox backend',
sandboxBackendDefault: 'Use deployment defaults',
sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',
sandboxBackendMissing: 'Config deleted',
sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',
sandboxInfoTitle: 'Why choose a backend?',
sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',
skillsInfoTitle: 'Skills란 무엇인가요?',
skillsInfoContent: 'Skills는 Agent에 특정 도메인의 지침, 워크플로 및 도구 지원을 제공하는 사전 설치된 전문 지식 모듈입니다. 활성화되면 Agent는 필요할 때 자동으로 관련 지식을 로드합니다.'
},

View File

@ -4652,6 +4652,101 @@ export default {
vectorStoreEngine: 'Движок векторной БД',
parserEngine: 'Движок парсинга',
storageEngine: 'Движок хранения',
sandbox: {
title: 'Sandbox Backend',
description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',
loading: 'Loading sandbox configuration...',
loadFailed: 'Failed to load sandbox configuration',
backend: 'Sandbox backend',
backendHint: 'Leave unset to inherit the global default',
addConfig: 'Add sandbox backend',
viewDeployDefaults: 'View deployment defaults',
deployDefaultsTitle: 'Deployment defaults',
deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',
deployDefaultBackend: 'Default backend',
apiKeyConfigured: 'Configured',
apiKeyNotConfigured: 'Not configured',
configName: 'Config name',
configNamePlaceholder: 'e.g. Production E2B',
configNameRequired: 'Please enter a config name',
configDescription: 'Description',
configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',
createTitle: 'Add sandbox backend',
editTitle: 'Edit sandbox backend',
noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
viewSandboxes: 'View sandbox usage',
inventoryTitle: 'Sandbox usage',
inventoryFailed: 'Failed to load sandbox usage',
sandboxCount: 'Sandboxes',
sandboxCountUnknown: 'Unknown (backend unreachable)',
inventoryUnverifiableHint: 'The backend is unreachable, so the sandbox count is unknown — that is not the same as none.',
sandboxesStillLive: 'This config still owns {count} running or paused sandbox(es), so identity fields cannot be changed yet.',
blockedHint: 'End or delete those sessions (deleting a session destroys its sandbox), or create a second config and point the agents at it.',
unverifiableBlocked: 'The backend cannot be reached to verify whether sandboxes remain, so the stored credentials will not be overwritten.',
unverifiableSaveHint: 'Restore connectivity first; if the backend is gone for good, create a second config and point the agents at it.',
affectedSessions: '{count} session(s) affected.',
affectedAgents: 'Agents using this config: {names}',
confirmDelete: 'Delete sandbox backend "{name}"?',
confirmDeleteWithAgents: 'Delete sandbox backend "{name}"? {agents}They will fail on their next skill execution.',
deleteFailed: 'Failed to delete',
deleted: 'Deleted',
forceDeleteTitle: 'Sandbox usage cannot be verified',
forceDeleteConfirm: 'The backend cannot be reached to verify whether sandboxes remain. If it is gone for good you can force-delete this config; if it is only temporarily unreachable, forcing it leaves any remaining sandboxes with nobody to reclaim them. Force delete anyway?',
forceDelete: 'Force delete',
disableScripts: 'Disable sandbox execution',
enableScripts: 'Enable sandbox execution',
disableScriptsConfirm:
'All agents in this workspace — will no longer run skill scripts in a sandbox. They can still read skill content. Existing remote sandboxes are not destroyed automatically; end or delete the related sessions to release them. Continue?',
scriptsDisabled: 'Sandbox execution disabled for this workspace',
scriptsEnabled: 'Sandbox execution restored for this workspace',
policySaveFailed: 'Failed to update sandbox execution policy',
legacyConfig: 'Deprecated',
namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',
fieldRequired: 'Required',
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
e2bApiUrlOptional: 'Optional — the SDK default is used when empty',
e2bDomainOptional: 'Optional — the SDK default is used when empty',
backends: {
disabled: 'Disabled',
local: 'Local process',
docker: 'Docker',
cube: 'CubeSandbox',
e2b: 'E2B',
},
apiUrl: 'API endpoint',
proxyUrl: 'Proxy endpoint',
sandboxDomain: 'Sandbox domain',
apiKey: 'API key',
templateId: 'Template ID',
httpTimeout: 'HTTP timeout (s)',
sandboxTtl: 'Sandbox TTL (s)',
dockerImage: 'Docker image',
defaultTimeout: 'Execution timeout (s)',
envVars: 'Environment variables',
envKey: 'Name',
envValue: 'Value',
envVarsHint: 'Injected into every sandbox for this workspace. Values are encrypted at rest but visible to scripts running inside the sandbox.',
addRow: 'Add variable',
removeRow: 'Remove',
save: 'Save',
saved: 'Saved. Applies to new sessions.',
saveFailed: 'Failed to save',
testConnection: 'Test connection',
deepCheck: 'Full verification',
deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',
checkPassed: 'All checks passed',
checkFailed: 'Some checks failed',
noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',
checks: {
client_build: 'Client construction',
api_url_reachable: 'Endpoint reachability',
credential_valid: 'Credential validity',
template_exists: 'Template existence',
sandbox_exec: 'In-sandbox execution',
egress_available: 'Outbound network',
},
},
mcpService: 'Сервис MCP',
versionInfo: 'Информация о версии',
taskQueue: 'Очереди задач',
@ -4896,6 +4991,13 @@ export default {
think: 'Размышление',
copy: 'Копировать',
addToKnowledgeBase: 'Добавить в базу знаний',
artifactDrawer: {
buttonTitle: 'Скачать файлы, сгенерированные в этом ответе',
title: 'Сгенерированные файлы',
empty: 'В этом раунде не создано файлов для скачивания.',
download: 'Скачать',
downloadFailed: 'Не удалось скачать, повторите попытку.',
},
updatePlan: 'Обновить план',
webSearchFound: 'Найдено <strong>{count}</strong> результатов веб‑поиска',
toolFallback: 'Инструмент',
@ -5039,6 +5141,15 @@ export default {
selectSkills: 'Выбрать Skills',
selectSkillsDesc: 'Выберите Skills для активации',
noSkillsAvailable: 'Нет доступных предустановленных Skills',
sandboxConfig: 'Sandbox backend',
sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',
sandboxBackend: 'Sandbox backend',
sandboxBackendDefault: 'Use deployment defaults',
sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',
sandboxBackendMissing: 'Config deleted',
sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',
sandboxInfoTitle: 'Why choose a backend?',
sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',
skillsInfoTitle: 'Что такое Skills?',
skillsInfoContent: 'Skills — это предустановленные модули профессиональных знаний, которые предоставляют агенту инструкции, рабочие процессы и инструменты для конкретных областей. При активации агент автоматически загружает соответствующие знания по мере необходимости.'
},

View File

@ -4652,6 +4652,101 @@ export default {
vectorStoreEngine: '向量数据库引擎',
parserEngine: '解析引擎',
storageEngine: '存储引擎',
sandbox: {
title: '沙箱后端',
description: '配置多份沙箱后端,智能体可各自选用其中一份。未填写的项沿用 .env 中的全局默认值。',
loading: '加载沙箱配置...',
loadFailed: '加载沙箱配置失败',
backend: '沙箱后端',
backendHint: '留空表示沿用全局默认',
addConfig: '添加沙箱后端',
viewDeployDefaults: '查看部署默认配置',
deployDefaultsTitle: '部署默认配置',
deployDefaultsHint: '来自 .env 的全局配置。配置里留空的项即沿用这里的值。',
deployDefaultBackend: '默认后端',
apiKeyConfigured: '已配置',
apiKeyNotConfigured: '未配置',
configName: '配置名称',
configNamePlaceholder: '如:生产 E2B',
configNameRequired: '请填写配置名称',
configDescription: '描述',
configDescriptionPlaceholder: '选填,用于区分多份同类型配置',
createTitle: '添加沙箱后端',
editTitle: '编辑沙箱后端',
noConfigs: '还没有沙箱后端配置。智能体将使用部署默认配置运行技能脚本。',
identityFieldHint: '该配置下有沙箱运行时,以下项无法修改:后端类型、API 端点、API Key、沙箱域名、Proxy 端点。',
viewSandboxes: '查看沙箱占用',
inventoryTitle: '沙箱占用',
inventoryFailed: '获取沙箱占用失败',
sandboxCount: '沙箱数量',
sandboxCountUnknown: '未知(无法连接该后端)',
inventoryUnverifiableHint: '无法连接该后端,因此沙箱数量未知——这不代表没有沙箱。',
sandboxesStillLive: '该配置仍有 {count} 个运行中或已暂停的沙箱,暂时无法修改身份字段。',
blockedHint: '可结束或删除这些会话(删除会话会销毁其沙箱),或新建一份配置并把智能体指过去。',
unverifiableBlocked: '无法连接该后端核实是否仍有沙箱,因此不能覆盖现有凭据。',
unverifiableSaveHint: '请先恢复该后端的连通性;若已废弃,可新建一份配置并把智能体指过去。',
affectedSessions: '影响 {count} 个会话。',
affectedAgents: '以下智能体正在使用该配置:{names}',
confirmDelete: '确定删除沙箱后端「{name}」吗?',
confirmDeleteWithAgents: '确定删除沙箱后端「{name}」吗?{agents}它们将在下次执行技能时报错。',
deleteFailed: '删除失败',
deleted: '已删除',
forceDeleteTitle: '无法核实沙箱占用',
forceDeleteConfirm: '无法连接该后端核实是否仍有沙箱。若该后端已废弃,可强制删除这份配置;若只是暂时不可达,强制删除会让残留沙箱无人回收。仍要强制删除吗?',
forceDelete: '强制删除',
disableScripts: '禁用沙盒执行',
enableScripts: '启用沙盒执行',
disableScriptsConfirm:
'禁用后,本空间内所有智能体将无法在沙盒中执行技能脚本;仍可阅读技能内容。已在运行中的远端沙盒不会自动销毁,需结束或删除相关会话后才会释放。是否继续?',
scriptsDisabled: '已禁用本空间沙盒执行',
scriptsEnabled: '已恢复本空间沙盒执行',
policySaveFailed: '更新沙盒执行策略失败',
legacyConfig: '已废弃',
namedBackendHint: '具名配置支持 CubeSandbox 与 E2B。',
fieldRequired: '必填',
cubeApiKeyOptional: '可留空 —— 自建 CubeSandbox 通常无鉴权',
e2bApiUrlOptional: '可留空 —— 留空时使用 SDK 默认值',
e2bDomainOptional: '可留空 —— 留空时使用 SDK 默认值',
backends: {
disabled: '禁用',
local: '本地进程',
docker: 'Docker',
cube: 'CubeSandbox',
e2b: 'E2B',
},
apiUrl: 'API 端点',
proxyUrl: 'Proxy 端点',
sandboxDomain: '沙箱域名',
apiKey: 'API Key',
templateId: '模板 ID',
httpTimeout: 'HTTP 超时(秒)',
sandboxTtl: '沙箱 TTL(秒)',
dockerImage: 'Docker 镜像',
defaultTimeout: '执行超时(秒)',
envVars: '环境变量',
envKey: '变量名',
envValue: '变量值',
envVarsHint: '注入到该空间所有沙箱;值加密存储,但对沙箱内脚本可见,请勿放入脚本不应读取的密钥。',
addRow: '添加变量',
removeRow: '删除',
save: '保存',
saved: '已保存,对新建会话生效',
saveFailed: '保存失败',
testConnection: '测试连接',
deepCheck: '完整验证',
deepCheckConfirm: '完整验证会真实创建并销毁一个沙箱,消耗少量沙箱时长,是否继续?',
checkPassed: '检测通过',
checkFailed: '检测未通过',
noVolumeSupport: '该后端不支持挂载卷,依赖共享卷的技能将不可用。',
checks: {
client_build: '客户端构建',
api_url_reachable: '端点可达性',
credential_valid: '凭据有效性',
template_exists: '模板存在性',
sandbox_exec: '沙箱内执行',
egress_available: '出网可用',
},
},
mcpService: 'MCP服务',
versionInfo: '版本信息',
taskQueue: '任务队列',
@ -4896,6 +4991,13 @@ export default {
think: '思考',
copy: '复制',
addToKnowledgeBase: '添加到知识库',
artifactDrawer: {
buttonTitle: '下载本次生成的文件',
title: '生成的文件',
empty: '本次未生成可下载的文件',
download: '下载',
downloadFailed: '下载失败,请稍后重试',
},
updatePlan: '更新计划',
webSearchFound: '找到 <strong>{count}</strong> 个网络搜索结果',
toolFallback: '工具',
@ -5039,6 +5141,15 @@ export default {
selectSkills: '选择 Skills',
selectSkillsDesc: '选择要启用的 Skills',
noSkillsAvailable: '暂无预装 Skills',
sandboxConfig: '沙箱后端',
sandboxConfigDesc: '选择该智能体的技能脚本在哪个沙箱后端中执行。',
sandboxBackend: '沙箱后端',
sandboxBackendDefault: '使用部署默认配置',
sandboxBackendHint: '仅在启用技能执行时生效。所选配置被删除后,该智能体的技能执行会失败。',
sandboxBackendMissing: '配置已删除',
sandboxNoConfigs: '当前空间还没有具名沙箱后端配置,技能脚本将运行在部署默认配置上。可在「设置 - 沙箱后端」中添加。',
sandboxInfoTitle: '为什么要选后端?',
sandboxInfoContent: '不同后端对应不同的账号、区域与配额。同一会话的沙箱一旦创建,后续的附件、产物与销毁都会锁定在创建时那份配置上,改这里只影响之后新建的沙箱。',
skillsInfoTitle: '什么是 Skills?',
skillsInfoContent: 'Skills 是预装的专业知识模块,可以为 Agent 提供特定领域的指令、工作流程和工具支持。启用 Skills 后,Agent 会在需要时自动加载相关知识。'
},

View File

@ -4,12 +4,13 @@ import { listKnowledgeBases, getKnowledgeBaseById } from '@/api/knowledge-base'
import { listAgents, type CustomAgent } from '@/api/agent'
import { listModels, type ModelConfig } from '@/api/model'
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider'
import { isNamedSandboxBackend, listSandboxConfigs, type SandboxConfigRecord } from '@/api/system'
import { useOrganizationStore } from '@/stores/organization'
/** 空间级资源缓存 TTL */
const CACHE_TTL_MS = 60_000
type ResourceKey = 'knowledgeBases' | 'agents' | 'models' | 'webSearchProviders'
type ResourceKey = 'knowledgeBases' | 'agents' | 'models' | 'webSearchProviders' | 'sandboxConfigs'
export type ListCreatorFilter = 'all' | 'mine' | 'others'
@ -27,6 +28,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
const disabledOwnAgentIds = ref<string[]>([])
const allModels = ref<ModelConfig[]>([])
const webSearchProviders = ref<WebSearchProviderEntity[]>([])
const sandboxConfigs = ref<SandboxConfigRecord[]>([])
const loadedAt = ref<Partial<Record<ResourceKey, number>>>({})
const inflight = new Map<ResourceKey, Promise<void>>()
@ -174,6 +176,30 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
})
}
/**
* 沙箱后端配置,供智能体编辑器的后端选择器使用。
*
* 不进 prefetchChatInput:只有编辑智能体时才需要,而对话输入栏用不到,
* 没必要让每次首屏都多打一次请求。
*
* 失败只吞掉不抛:这是可选资源——拿不到就只剩「使用部署默认配置」一项,
* 智能体照样能编辑保存。调用方通常把它和一堆必需资源放在同一个
* Promise.all 里,若在这里抛出,整个编辑器的依赖加载都会连坐
* (技能可用性拿不到 ⇒ 技能配置分组直接消失)。
*/
async function ensureSandboxConfigs(force = false): Promise<void> {
return runOnce('sandboxConfigs', force, async () => {
try {
const res = await listSandboxConfigs()
const rows = Array.isArray(res?.data) ? res.data : []
sandboxConfigs.value = rows.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type))
} catch {
sandboxConfigs.value = []
}
loadedAt.value.sandboxConfigs = Date.now()
})
}
/** 并行预取对话输入栏及列表页常用的空间级资源 */
async function prefetchChatInput(force = false): Promise<void> {
const orgStore = useOrganizationStore()
@ -258,6 +284,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
disabledOwnAgentIds.value = []
allModels.value = []
webSearchProviders.value = []
sandboxConfigs.value = []
agentKbCache.clear()
// 同时丢弃所有 inflight 句柄,否则失效后仍在飞行的请求会把旧数据写回缓存。
inflight.clear()
@ -290,6 +317,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
allModels,
chatModels,
webSearchProviders,
sandboxConfigs,
isFresh,
fetchKnowledgeBasesForList,
fetchAgentsForList,
@ -298,6 +326,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
ensureModels,
ensureChatModels,
ensureWebSearchProviders,
ensureSandboxConfigs,
ensureAgentKnowledgeBases,
prefetchChatInput,
fetchKnowledgeBaseById,

View File

@ -1289,6 +1289,46 @@
</div>
</div>
<!-- 沙箱后端配置(仅 Agent 模式):技能脚本的运行环境 -->
<div v-show="currentSection === 'sandbox' && isAgentMode" class="section">
<div class="section-header">
<h2>{{ $t('agent.editor.sandboxConfig') }}</h2>
<p class="section-description">{{ $t('agent.editor.sandboxConfigDesc') }}</p>
</div>
<div class="settings-group">
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agent.editor.sandboxBackend') }}</label>
<p class="desc">{{ $t('agent.editor.sandboxBackendHint') }}</p>
</div>
<div class="setting-control">
<t-select v-model="formData.config.sandbox_config_id"
:placeholder="$t('agent.editor.sandboxBackendDefault')" style="width: 280px">
<t-option value="" :label="$t('agent.editor.sandboxBackendDefault')" />
<t-option v-for="cfg in sandboxConfigOptions" :key="cfg.id" :value="cfg.id"
:label="`${cfg.name} (${backendLabel(cfg.sandbox_type)})`" />
</t-select>
</div>
</div>
<!-- 未建具名配置时说明「默认」到底是什么,避免下拉只有一项时显得像坏了 -->
<div v-if="sandboxConfigOptions.length === 0" class="setting-row">
<div class="setting-info">
<p class="desc empty-hint">{{ $t('agent.editor.sandboxNoConfigs') }}</p>
</div>
</div>
<div class="skill-info-box">
<t-icon name="cloud" class="info-icon" />
<div class="info-content">
<p><strong>{{ $t('agent.editor.sandboxInfoTitle') }}</strong></p>
<p>{{ $t('agent.editor.sandboxInfoContent') }}</p>
</div>
</div>
</div>
</div>
<!-- 知识库配置 -->
<div v-show="currentSection === 'knowledge'" class="section">
<div class="section-header">
@ -1665,7 +1705,13 @@ import { type ModelConfig } from '@/api/model';
import { type AgentNotReadyReasonKey, agentRequiresRerankModel } from '@/utils/agent-readiness';
import { type SkillInfo } from '@/api/skill';
import { type WebSearchProviderEntity } from '@/api/web-search-provider';
import { type StorageEngineStatusItem, type PromptTemplate, type PromptTemplatesConfig } from '@/api/system';
import {
isNamedSandboxBackend,
type SandboxConfigRecord,
type StorageEngineStatusItem,
type PromptTemplate,
type PromptTemplatesConfig,
} from '@/api/system';
import { useUIStore } from '@/stores/ui';
import { useAuthStore } from '@/stores/auth';
import { useOrganizationStore } from '@/stores/organization';
@ -1885,6 +1931,19 @@ const webSearchProviderList = ref<WebSearchProviderEntity[]>([]);
const skillOptions = ref<{ name: string; description: string }[]>([]);
// 是否允许启用 Skills(取决于后端沙箱是否启用,disabled 时为 false;未请求前为 false 避免闪显)
const skillsAvailable = ref(false);
// 空间内的具名沙箱后端配置。始终包含当前已选中的那份,即使它已被删除——
// 否则下拉会静默显示为"使用部署默认配置",看不出该智能体其实指着一份不存在的配置。
const sandboxConfigOptions = computed(() => {
const configs = chatResources.sandboxConfigs.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type));
const selected = formData.value.config.sandbox_config_id;
if (!selected || configs.some((cfg) => cfg.id === selected)) return configs;
return [
...configs,
{ id: selected, name: t('agent.editor.sandboxBackendMissing'), sandbox_type: '' } as SandboxConfigRecord,
];
});
const backendLabel = (type: string) =>
type ? t(`settings.sandbox.backends.${type}`) : t('common.error');
// 存储引擎可用状态(用于图片存储 provider 选择)
const storageEngineStatus = ref<StorageEngineStatusItem[]>([]);
const imageStorageOptions = computed(() => {
@ -2248,6 +2307,9 @@ const navItems = computed(() => {
}
if (isAgentMode.value && skillsAvailable.value) {
items.push({ key: 'skills', icon: 'lightbulb', label: t('agent.editor.skillsConfig') });
// 沙箱是技能脚本的运行环境:先选跑哪些技能,再选跑在哪份后端上。
// 与 skills 同门控——部署级沙箱关闭时技能整体不可用,选后端也就无从谈起。
items.push({ key: 'sandbox', icon: 'cloud', label: t('agent.editor.sandboxConfig') });
}
// 发布(仅编辑模式)
if (editorMode.value === 'edit' && editorAgent.value?.id && !editorAgent.value?.is_builtin && !authStore.isLiteMode) {
@ -2275,7 +2337,7 @@ const navGroups = computed(() => {
{
key: 'capability',
label: t('agentEditor.navGroups.capability'),
items: pickItems(['multimodal', 'tools', 'mcp', 'skills']),
items: pickItems(['multimodal', 'tools', 'mcp', 'skills', 'sandbox']),
},
{
key: 'integration',
@ -2315,6 +2377,8 @@ const defaultFormData = {
// Skills 设置
skills_selection_mode: 'none' as 'all' | 'selected' | 'none',
selected_skills: [] as string[],
// 技能脚本运行在哪份沙箱后端配置上。留空表示使用部署默认配置。
sandbox_config_id: '' as string,
// 知识库设置:新建智能体默认选择 "全部知识库",
// 让用户无需先去勾选 KB 即可上手;如有需要可改为 "selected" / "none"。
kb_selection_mode: 'all' as 'all' | 'selected' | 'none',
@ -3345,6 +3409,7 @@ const loadDependencies = async () => {
chatResources.ensureModels(),
chatResources.ensureKnowledgeBases(),
chatResources.ensureWebSearchProviders(),
chatResources.ensureSandboxConfigs(),
editorResources.prefetchAgentEditorDeps(),
]);

View File

@ -315,6 +315,23 @@
:title="$t('agent.addToKnowledgeBase')">
<t-icon name="bookmark-add" />
</t-button>
<!-- Skill artifact download: only shown when the persisted
assistant message recorded any generated files. Agent
mode is the primary path for skills, so this is where
the button is most likely to appear. -->
<t-badge
v-if="hasArtifacts"
:count="artifactCount"
:offset="[-4, 4]"
shape="round"
size="small"
>
<t-button size="small" variant="outline" shape="round"
@click.stop="openArtifactDrawer"
:title="$t('agent.artifactDrawer.buttonTitle')">
<t-icon name="download" />
</t-button>
</t-badge>
<t-tooltip v-if="event.is_fallback" :content="$t('chat.fallbackHint')" placement="top">
<t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">
<t-icon name="info-circle" />
@ -479,6 +496,13 @@
</div>
</template>
</t-drawer>
<ChatArtifactsDrawer
v-if="hasArtifacts && sessionIdForArtifacts && messageIdForArtifacts"
v-model:visible="showArtifactDrawer"
:session-id="sessionIdForArtifacts"
:message-id="messageIdForArtifacts"
:artifacts="artifactList"
/>
</template>
<script setup lang="ts">
@ -492,6 +516,7 @@ import McpOAuthCard from './McpOAuthCard.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';
import { countGrepDocuments, groupGrepChunkResults } from '@/utils/grepResultsGroup';
import { getKnowledgeChunksSummaryHtml } from '@/utils/knowledgeChunksDisplay';
import { getAttachmentParsingSummaryHtml } from '@/utils/attachmentParsingDisplay';
@ -856,6 +881,30 @@ watch(
},
);
// -----------------------------------------------------------------------------
// Skill artifact download drawer (Agent path)
// -----------------------------------------------------------------------------
// Same contract as botmsg.vue: only render the button when the persisted
// assistant message actually recorded files, then let ChatArtifactsDrawer
// resolve names/sizes/mtimes and stream downloads via the /artifacts
// endpoint. Agent mode is the primary path for skills, so this button will
// appear more often here than in the RAG path.
const showArtifactDrawer = ref(false);
const artifactList = computed(() => {
const list = ((props.session?.artifacts as any[]) || []);
return list.map((a, i) => ({ index: i, ...a }));
});
const hasArtifacts = computed(() => artifactList.value.length > 0);
const artifactCount = computed(() => artifactList.value.length);
const sessionIdForArtifacts = computed(() => props.sessionId ?? '');
const messageIdForArtifacts = computed(() =>
String(props.session?.id || props.session?.request_id || ''),
);
function openArtifactDrawer() {
if (!hasArtifacts.value) return;
showArtifactDrawer.value = true;
}
const {
float: citationFloat,
rebind: rebindCitations,

View File

@ -0,0 +1,307 @@
<template>
<!--
ChatArtifactsDrawer — right-side drawer that lists every skill-generated
file attached to the surrounding assistant message.
Usage (from botmsg.vue / AgentStreamDisplay.vue):
<ChatArtifactsDrawer
v-model:visible="showArtifacts"
:session-id="sessionId"
:message-id="messageId"
:artifacts="artifacts"
/>
The list is driven by whatever the parent has already resolved from
the streamed message payload. When the parent has no local copy
(e.g. after a page refresh) it can pass an empty array and the
drawer will pull the metadata itself via /artifacts.
-->
<t-drawer
v-model:visible="internalVisible"
placement="right"
size="440px"
attach="body"
:header="$t('agent.artifactDrawer.title')"
:footer="false"
:close-on-overlay-click="true"
:destroy-on-close="false"
@close="handleClose"
>
<div v-if="loading" class="artifact-drawer-empty">
<t-loading size="small" />
<span>{{ $t('common.loading') }}</span>
</div>
<div v-else-if="!items.length" class="artifact-drawer-empty">
<t-icon name="folder-open" size="32" />
<span>{{ $t('agent.artifactDrawer.empty') }}</span>
</div>
<t-list v-else split :size="'medium'">
<t-list-item v-for="item in items" :key="`${item.index}-${item.file_name}`" class="artifact-item">
<div class="artifact-icon">
<t-icon :name="iconForFile(item.file_name)" size="24" />
</div>
<div class="artifact-body">
<div class="artifact-name" :title="item.file_name">{{ item.file_name }}</div>
<div class="artifact-meta">
<span>{{ formatFileSize(item.file_size) }}</span>
<span class="artifact-meta-sep">·</span>
<span>{{ formatDateTime(item.created_at) }}</span>
</div>
</div>
<t-button
size="small"
variant="outline"
shape="round"
:loading="!!downloading[item.index]"
@click.stop="handleDownload(item)"
>
<t-icon name="download" />
<span class="artifact-download-label">
{{ $t('agent.artifactDrawer.download') }}
</span>
</t-button>
</t-list-item>
</t-list>
</t-drawer>
</template>
<script setup lang="ts">
/*
* Design notes:
* - The drawer is stateless w.r.t. the download itself; it delegates to
* the chat API's downloadArtifact() helper which uses the axios blob
* transport (getDown) so the Bearer token stays attached — plain
* <a href> would drop it and hit 401.
* - `items` prefers the props-provided list (already in memory from the
* stream payload). When empty, we pull from /artifacts on open so a
* refreshed page still shows something without waiting for the parent
* to re-hydrate.
* - Errors during download are surfaced via MessagePlugin.error but do
* NOT close the drawer, matching spec §7: "抽屉保持打开以便重试其他文件".
*/
import { computed, ref, watch, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { downloadArtifact, listMessageArtifacts, type ArtifactMeta } from '@/api/chat'
const props = defineProps<{
visible: boolean
sessionId: string
messageId: string
artifacts?: ArtifactMeta[]
}>()
const emit = defineEmits<{
(e: 'update:visible', v: boolean): void
}>()
const { t } = useI18n()
// Two-way binding shim so `v-model:visible` works while the parent still
// owns the source of truth.
const internalVisible = computed({
get: () => props.visible,
set: (v: boolean) => emit('update:visible', v),
})
const loading = ref(false)
const fetched = ref<ArtifactMeta[]>([])
const downloading = reactive<Record<number, boolean>>({})
const items = computed<ArtifactMeta[]>(() => {
if (props.artifacts && props.artifacts.length) return props.artifacts
return fetched.value
})
// Refresh /artifacts when the drawer opens without a caller-provided list.
// Cheap when the caller already passed artifacts; a real request only when
// the parent's copy is empty (e.g. right after page refresh, before message
// hydration finishes).
watch(
() => props.visible,
async (open) => {
if (!open) return
if (props.artifacts && props.artifacts.length) {
fetched.value = []
return
}
if (!props.sessionId || !props.messageId) return
loading.value = true
try {
const res: any = await listMessageArtifacts(props.sessionId, props.messageId)
const data = (res && (res.data || res)) as ArtifactMeta[] | undefined
fetched.value = Array.isArray(data) ? data : []
} catch (err) {
console.error('[ChatArtifactsDrawer] load failed:', err)
fetched.value = []
} finally {
loading.value = false
}
},
)
function handleClose() {
emit('update:visible', false)
}
// Format helpers.
function formatFileSize(size: number): string {
if (!size || size < 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB']
let s = size
let unit = 0
while (s >= 1024 && unit < units.length - 1) {
s /= 1024
unit++
}
// Keep one decimal for non-integer units; integers stay integer.
return unit === 0 ? `${s} ${units[unit]}` : `${s.toFixed(1)} ${units[unit]}`
}
function formatDateTime(raw: string): string {
if (!raw) return '—'
const d = new Date(raw)
if (Number.isNaN(d.getTime())) return raw
// Local time, seconds precision — matches how the rest of the app
// renders message timestamps.
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
function iconForFile(name: string): string {
const ext = (name.split('.').pop() || '').toLowerCase()
switch (ext) {
case 'pptx':
case 'ppt':
return 'chart-pie'
case 'xlsx':
case 'xls':
case 'csv':
return 'file-excel'
case 'docx':
case 'doc':
return 'file-word'
case 'pdf':
return 'file-pdf'
case 'md':
case 'markdown':
return 'file'
case 'html':
case 'htm':
return 'code-1'
case 'json':
return 'code-1'
case 'png':
case 'jpg':
case 'jpeg':
case 'gif':
case 'svg':
case 'webp':
return 'image'
case 'mp3':
case 'wav':
case 'ogg':
return 'sound-up'
case 'mp4':
case 'mov':
case 'webm':
return 'video'
case 'zip':
case 'tar':
case 'gz':
return 'folder-zip'
default:
return 'file-attachment'
}
}
async function handleDownload(item: ArtifactMeta) {
if (!props.sessionId || !props.messageId) {
MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
return
}
downloading[item.index] = true
try {
const blob = await downloadArtifact(props.sessionId, props.messageId, item.index)
// Trigger browser save via an object URL so the file name comes
// through even when the server's Content-Disposition is stripped
// by an intermediate proxy.
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = item.file_name || 'artifact'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
// Give the browser a tick to start the download before revoking.
setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (err) {
console.error('[ChatArtifactsDrawer] download failed:', err)
MessagePlugin.error(t('agent.artifactDrawer.downloadFailed'))
} finally {
downloading[item.index] = false
}
}
</script>
<style lang="less" scoped>
.artifact-drawer-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
padding: 48px 16px;
color: var(--td-text-color-placeholder);
font-size: 13px;
}
.artifact-item {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 4px;
.artifact-icon {
flex-shrink: 0;
width: 36px;
height: 36px;
border-radius: 8px;
background: var(--td-bg-color-container-hover);
display: flex;
align-items: center;
justify-content: center;
color: var(--td-brand-color);
}
.artifact-body {
flex: 1;
min-width: 0;
}
.artifact-name {
font-size: 14px;
color: var(--td-text-color-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.artifact-meta {
margin-top: 2px;
font-size: 12px;
color: var(--td-text-color-placeholder);
display: flex;
gap: 4px;
align-items: center;
}
.artifact-meta-sep {
opacity: 0.6;
}
.artifact-download-label {
margin-left: 4px;
}
}
</style>

View File

@ -46,6 +46,23 @@
:title="$t('agent.addToKnowledgeBase')">
<t-icon name="bookmark-add" />
</t-button>
<!-- Skill artifact download: only shown when this reply's
assistant message actually recorded any generated files.
Emptiness is the default: the button stays hidden for
conversational messages that never touched a skill. -->
<t-badge
v-if="hasArtifacts"
:count="artifactCount"
:offset="[-4, 4]"
shape="round"
size="small"
>
<t-button size="small" variant="outline" shape="round"
@click.stop="openArtifactDrawer"
:title="$t('agent.artifactDrawer.buttonTitle')">
<t-icon name="download" />
</t-button>
</t-badge>
<!-- Fallback 提示图标 -->
<t-tooltip v-if="session.is_fallback" :content="$t('chat.fallbackHint')" placement="top">
<t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">
@ -69,6 +86,13 @@
<ChatCitationFloat :float="citationFloat" :on-enter="cancelCitationClose"
:on-leave="scheduleCitationClose" />
</Teleport>
<ChatArtifactsDrawer
v-if="hasArtifacts"
v-model:visible="showArtifactDrawer"
:session-id="sessionId"
:message-id="messageIdForArtifacts"
:artifacts="artifactList"
/>
</div>
</template>
<script setup>
@ -81,6 +105,7 @@ import RagPipelineProgress from './RagPipelineProgress.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';
import { sanitizeMarkdownHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security';
import { useI18n } from 'vue-i18n';
import { MessagePlugin } from 'tdesign-vue-next';
@ -165,6 +190,40 @@ const props = defineProps({
const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
// -----------------------------------------------------------------------------
// Skill artifact download (drawer)
// -----------------------------------------------------------------------------
// The download button and drawer are opt-in per message: the toolbar checks
// `hasArtifacts` and only renders when the assistant message actually
// recorded a file. `messageIdForArtifacts` resolves to whichever field the
// caller uses to identify the row on the server (session.id from the SSE
// hydration path, request_id when the caller pre-populated it).
//
// NOTE: this file's <script setup> block is plain JS (no lang="ts"), so we
// stay away from TypeScript-only syntax like `as any[]` — the vite Vue
// plugin routes non-TS blocks through babel which rejects those tokens.
const showArtifactDrawer = ref(false);
const artifactList = computed(() => {
const raw = props.session && props.session.artifacts;
const list = Array.isArray(raw) ? raw : [];
// Enrich each entry with its position so the download endpoint can
// resolve it. Server responses already include `index` when they come
// via listMessageArtifacts; SSE payloads that land through Message.Artifacts
// omit it. Normalising here keeps ChatArtifactsDrawer index-agnostic.
return list.map((a, i) => ({ index: i, ...a }));
});
const hasArtifacts = computed(() => artifactList.value.length > 0);
const artifactCount = computed(() => artifactList.value.length);
const messageIdForArtifacts = computed(() => {
// Prefer the persistent message ID; fall back to request_id for the
// in-flight path where the SSE stream still identifies rows by request.
return String((props.session && (props.session.id || props.session.request_id)) || '');
});
function openArtifactDrawer() {
if (!hasArtifacts.value) return;
showArtifactDrawer.value = true;
}
const preview = (url) => {
nextTick(() => {
reviewUrl.value = url;

View File

@ -0,0 +1,706 @@
<template>
<div class="sandbox-settings">
<div class="section-header">
<div class="section-header__top">
<div>
<h2>{{ $t('settings.sandbox.title') }}</h2>
<p class="section-description">{{ $t('settings.sandbox.description') }}</p>
<p class="section-description section-description--hint">{{ $t('settings.sandbox.namedBackendHint') }}</p>
</div>
<t-button theme="primary" variant="text" size="medium" class="defaults-trigger" @click="showDefaults = true">
<template #icon><t-icon name="info-circle" /></template>
{{ $t('settings.sandbox.viewDeployDefaults') }}
</t-button>
</div>
</div>
<div class="sandbox-tabs-row">
<t-tabs v-model="activeType" class="sandbox-type-tabs">
<t-tab-panel value="all" :label="`${$t('common.all')}(${records.length})`" />
<t-tab-panel v-for="type in backendTypes" :key="type" :value="type"
:label="`${backendLabel(type)}(${countByType(type)})`" />
</t-tabs>
<div class="sandbox-tabs-actions">
<t-button v-if="!workspaceScriptsDisabled" variant="outline" theme="danger" size="medium"
:loading="policySaving" @click="confirmDisableScripts">
{{ $t('settings.sandbox.disableScripts') }}
</t-button>
<t-button v-else variant="outline" theme="primary" size="medium" :loading="policySaving"
@click="enableScripts">
{{ $t('settings.sandbox.enableScripts') }}
</t-button>
</div>
</div>
<t-loading :loading="loading" size="small" class="sandbox-list-loading">
<div v-if="!loading" class="sandbox-grid">
<div v-for="record in filteredRecords" :key="record.id" class="sandbox-card"
:class="`sandbox-card--${record.sandbox_type}`">
<div class="sandbox-card__badge">
<t-icon :name="typeIcon(record.sandbox_type)" size="18px" />
</div>
<div class="sandbox-card__body">
<div class="sandbox-card__header">
<h3 class="sandbox-card__title">{{ record.name }}</h3>
<div class="sandbox-card__actions" @click.stop>
<t-dropdown :options="cardMenu(record)" trigger="click" attach="body" placement="bottom-right"
@click="(data: any) => onMenuAction(data.value, record)">
<t-button variant="text" shape="square" size="small" class="sandbox-card__action-btn">
<t-icon name="ellipsis" />
</t-button>
</t-dropdown>
<t-tooltip :content="$t('common.delete')" placement="top">
<t-button theme="danger" shape="square" variant="text" size="small"
class="sandbox-card__action-btn" @click.stop="confirmDelete(record)">
<template #icon><t-icon name="delete" /></template>
</t-button>
</t-tooltip>
</div>
</div>
<p class="sandbox-card__subtitle">
<span>{{ backendLabel(record.sandbox_type) }}</span>
<t-tag v-if="isLegacyRecord(record)" theme="warning" variant="light" size="small" class="legacy-tag">
{{ $t('settings.sandbox.legacyConfig') }}
</t-tag>
<template v-if="endpointHost(record)">
<span class="sandbox-card__sep">·</span>
<span>{{ endpointHost(record) }}</span>
</template>
</p>
<p v-if="record.description" class="sandbox-card__desc">{{ record.description }}</p>
</div>
</div>
<button type="button" class="sandbox-card sandbox-card--add" @click="openCreate">
<span class="sandbox-card--add__icon" aria-hidden="true"><t-icon name="add" /></span>
<span class="sandbox-card--add__label">{{ $t('settings.sandbox.addConfig') }}</span>
</button>
</div>
<p v-if="!loading && records.length === 0" class="sandbox-empty-hint">
{{ $t('settings.sandbox.noConfigs') }}
</p>
</t-loading>
<SandboxConfigEditorDrawer v-model:visible="showEditor" :record="editingRecord"
:preset-type="activeType === 'all' ? '' : activeType" :defaults="defaults" @saved="load" />
<t-dialog v-model:visible="showDefaults" :header="$t('settings.sandbox.deployDefaultsTitle')" width="560px"
:cancel-btn="null" :confirm-btn="{ content: $t('common.close') }" @confirm="showDefaults = false">
<p class="dialog-hint">{{ $t('settings.sandbox.deployDefaultsHint') }}</p>
<ul class="defaults-list">
<li>
<span class="defaults-label">{{ $t('settings.sandbox.deployDefaultBackend') }}</span>
<span>{{ defaults?.sandbox_type ? backendLabel(defaults.sandbox_type) : '-' }}</span>
</li>
<template v-for="provider in defaultProviders" :key="provider.type">
<li class="defaults-group">{{ backendLabel(provider.type) }}</li>
<li v-for="row in provider.rows" :key="row.label">
<span class="defaults-label">{{ row.label }}</span>
<span>{{ row.value }}</span>
</li>
</template>
</ul>
</t-dialog>
<t-dialog v-model:visible="showInventory" :header="$t('settings.sandbox.inventoryTitle')" width="520px"
:cancel-btn="null" :confirm-btn="{ content: $t('common.close') }" @confirm="showInventory = false">
<t-loading :loading="inventoryLoading" size="small">
<div v-if="inventory" class="inventory">
<t-alert v-if="inventory.unverifiable" theme="warning"
:message="$t('settings.sandbox.inventoryUnverifiableHint')" />
<ul class="defaults-list">
<li>
<span class="defaults-label">{{ $t('settings.sandbox.sandboxCount') }}</span>
<span>{{ inventory.unverifiable
? $t('settings.sandbox.sandboxCountUnknown')
: inventory.sandbox_count }}</span>
</li>
<li v-if="inventory.session_ids?.length">
<span class="defaults-label">{{ $t('settings.sandbox.affectedSessions', {
count: inventory.session_ids.length }) }}</span>
</li>
<li v-if="inventory.agent_names?.length">
<span class="defaults-label">{{ $t('settings.sandbox.affectedAgents', {
names: inventory.agent_names.join('、') }) }}</span>
</li>
</ul>
</div>
</t-loading>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import SandboxConfigEditorDrawer from '@/components/SandboxConfigEditorDrawer.vue'
import {
checkSandboxConfig,
deleteSandboxConfig,
getSandboxConfigInventory,
isNamedSandboxBackend,
listSandboxConfigs,
parseSandboxConflict,
setSandboxWorkspacePolicy,
type SandboxConfigDefaults,
type SandboxConfigRecord,
type SandboxInventory,
} from '@/api/system'
const { t } = useI18n()
const backendTypes = ['cube', 'e2b'] as const
const loading = ref(false)
const policySaving = ref(false)
const workspaceScriptsDisabled = ref(false)
const records = ref<SandboxConfigRecord[]>([])
const defaults = ref<SandboxConfigDefaults | null>(null)
const activeType = ref<string>('all')
const showEditor = ref(false)
const editingRecord = ref<SandboxConfigRecord | null>(null)
const showDefaults = ref(false)
const showInventory = ref(false)
const inventoryLoading = ref(false)
const inventory = ref<SandboxInventory | null>(null)
const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)
const typeIcon = (type: string) => {
if (type === 'docker' || type === 'local') return 'server'
if (type === 'disabled') return 'minus-circle'
return 'cloud'
}
const isLegacyRecord = (record: SandboxConfigRecord) => !isNamedSandboxBackend(record.sandbox_type)
const filteredRecords = computed(() => {
const base = activeType.value === 'all'
? records.value
: records.value.filter((r) => r.sandbox_type === activeType.value)
return base
})
const countByType = (type: string) =>
records.value.filter((r) => r.sandbox_type === type && isNamedSandboxBackend(r.sandbox_type)).length
const cardMenu = (record: SandboxConfigRecord) => {
if (isLegacyRecord(record)) {
return [{ content: t('common.delete'), value: 'delete-only' }]
}
return [
{ content: t('common.edit'), value: 'edit' },
{ content: t('settings.sandbox.testConnection'), value: 'check' },
{ content: t('settings.sandbox.viewSandboxes'), value: 'inventory' },
]
}
// The endpoint host is what tells two configs of the same backend apart at a
// glance, which is the whole point of allowing several of them.
function endpointHost(record: SandboxConfigRecord): string {
const raw = record.config?.e2b?.api_url || record.config?.cube?.api_url || ''
if (!raw) return ''
try {
return new URL(raw).host
} catch {
return raw
}
}
const defaultProviders = computed(() => {
const groups: { type: string; rows: { label: string; value: string }[] }[] = []
const describe = (type: 'cube' | 'e2b') => {
const provider = defaults.value?.[type]
if (!provider) return
const rows = [
{ label: t('settings.sandbox.apiUrl'), value: provider.api_url || '-' },
...(type === 'cube'
? [{ label: t('settings.sandbox.proxyUrl'), value: provider.proxy_url || '-' }]
: []),
{ label: t('settings.sandbox.sandboxDomain'), value: provider.sandbox_domain || '-' },
{ label: t('settings.sandbox.templateId'), value: provider.template_id || '-' },
{
label: t('settings.sandbox.apiKey'),
value: provider.api_key_configured
? t('settings.sandbox.apiKeyConfigured')
: t('settings.sandbox.apiKeyNotConfigured'),
},
]
groups.push({ type, rows })
}
describe('cube')
describe('e2b')
return groups
})
// Agent references never block deletion, but the admin has to see which agents
// will start failing — otherwise the breakage is discovered mid-conversation.
// The inventory is fetched first purely for that warning; the DELETE itself is
// still the authoritative check.
async function confirmDelete(record: SandboxConfigRecord) {
let agents: string[] = []
try {
const res = await getSandboxConfigInventory(record.id)
agents = res?.data?.agent_names || []
} catch {
// An unreachable backend must not stop the admin from trying to delete.
}
const body = agents.length
? t('settings.sandbox.confirmDeleteWithAgents', {
name: record.name,
agents: t('settings.sandbox.affectedAgents', { names: agents.join('、') }) + ' ',
})
: t('settings.sandbox.confirmDelete', { name: record.name })
const dialog = DialogPlugin.confirm({
header: t('common.confirmDelete'),
body,
theme: 'warning',
confirmBtn: { content: t('common.delete'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: async () => {
dialog.destroy()
await removeRecord(record)
},
})
}
function openCreate() {
editingRecord.value = null
showEditor.value = true
}
async function load() {
loading.value = true
try {
const res = await listSandboxConfigs()
records.value = res?.data || []
defaults.value = res?.defaults || null
workspaceScriptsDisabled.value = res?.workspace_scripts_disabled === true
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.loadFailed'))
} finally {
loading.value = false
}
}
function confirmDisableScripts() {
const dialog = DialogPlugin.confirm({
header: t('settings.sandbox.disableScripts'),
body: t('settings.sandbox.disableScriptsConfirm'),
theme: 'warning',
confirmBtn: { content: t('settings.sandbox.disableScripts'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: async () => {
dialog.destroy()
await setScriptsDisabled(true)
},
})
}
async function enableScripts() {
await setScriptsDisabled(false)
}
async function setScriptsDisabled(disabled: boolean) {
policySaving.value = true
try {
const res = await setSandboxWorkspacePolicy(disabled)
workspaceScriptsDisabled.value = res?.workspace_scripts_disabled === true
MessagePlugin.success(
disabled ? t('settings.sandbox.scriptsDisabled') : t('settings.sandbox.scriptsEnabled'),
)
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.policySaveFailed'))
} finally {
policySaving.value = false
}
}
async function onMenuAction(action: string, record: SandboxConfigRecord) {
if (action === 'delete-only') {
confirmDelete(record)
return
}
if (action === 'edit') {
editingRecord.value = record
showEditor.value = true
return
}
if (action === 'check') {
await runQuickCheck(record)
return
}
if (action === 'inventory') {
await openInventory(record)
}
}
// A card-level probe answers "is this backend still alive" without opening the
// form; the per-probe breakdown and the sandbox-consuming deep check stay in the
// editor, where the config being probed is on screen.
async function runQuickCheck(record: SandboxConfigRecord) {
try {
const res = await checkSandboxConfig({ config_id: record.id })
const result = res?.data
if (result?.ok) {
MessagePlugin.success(t('settings.sandbox.checkPassed'))
return
}
const failed = result?.checks?.find((item) => item.ok === false)
MessagePlugin.error(failed?.message || t('settings.sandbox.checkFailed'))
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.checkFailed'))
}
}
async function openInventory(record: SandboxConfigRecord) {
showInventory.value = true
inventoryLoading.value = true
inventory.value = null
try {
const res = await getSandboxConfigInventory(record.id)
inventory.value = res?.data || null
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.inventoryFailed'))
showInventory.value = false
} finally {
inventoryLoading.value = false
}
}
async function removeRecord(record: SandboxConfigRecord, force = false) {
try {
await deleteSandboxConfig(record.id, force)
MessagePlugin.success(t('settings.sandbox.deleted'))
await load()
} catch (e: any) {
const refusal = parseSandboxConflict(e)
if (refusal?.code === 'sandboxes_still_live') {
// Counted sandboxes are never overridable: forcing the row away would
// leave paused instances nobody can reach, billing indefinitely.
showStillLiveDialog(refusal.inventory)
return
}
if (refusal?.code === 'sandbox_inventory_unverifiable') {
confirmForceDelete(record)
return
}
MessagePlugin.error(e?.message || t('settings.sandbox.deleteFailed'))
}
}
function showStillLiveDialog(inv?: SandboxInventory) {
const lines = [t('settings.sandbox.sandboxesStillLive', { count: inv?.sandbox_count ?? 0 })]
if (inv?.session_ids?.length) {
lines.push(t('settings.sandbox.affectedSessions', { count: inv.session_ids.length }))
}
lines.push(t('settings.sandbox.blockedHint'))
const dialog = DialogPlugin.alert({
header: t('settings.sandbox.inventoryTitle'),
// A dialog body is plain text, so newlines would collapse.
body: lines.join(' '),
confirmBtn: t('common.close'),
onConfirm: () => dialog.destroy(),
})
}
// Deleting is the one action with no second way out: an endpoint whose DNS
// record is gone can never be verified again, so the row would be permanently
// undeletable. The admin takes that call explicitly.
function confirmForceDelete(record: SandboxConfigRecord) {
const dialog = DialogPlugin.confirm({
header: t('settings.sandbox.forceDeleteTitle'),
body: t('settings.sandbox.forceDeleteConfirm'),
theme: 'warning',
confirmBtn: { content: t('settings.sandbox.forceDelete'), theme: 'danger' },
cancelBtn: t('common.cancel'),
onConfirm: async () => {
dialog.destroy()
await removeRecord(record, true)
},
})
}
onMounted(load)
</script>
<style lang="less" scoped>
.sandbox-settings {
padding: 4px 0;
}
.section-header h2 {
margin: 0 0 6px;
font-size: 18px;
font-weight: 600;
}
.section-description {
margin: 0 0 20px;
color: var(--td-text-color-secondary);
font-size: 13px;
&--hint {
margin-top: -12px;
margin-bottom: 20px;
}
}
.section-header__top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
}
.defaults-trigger {
--td-bg-color-container-hover: transparent;
flex-shrink: 0;
padding-left: 0;
padding-right: 0;
font-weight: 600;
}
.sandbox-list-loading {
min-height: 120px;
}
.sandbox-tabs-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 16px;
}
.sandbox-tabs-actions {
flex-shrink: 0;
padding-top: 4px;
}
.sandbox-type-tabs {
flex: 1;
min-width: 0;
margin-bottom: 0;
:deep(.t-tabs__nav-item) {
font-size: 13px;
}
:deep(.t-tabs__content) {
display: none;
}
}
.sandbox-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 12px;
.sandbox-card--add {
width: 100%;
height: 100%;
}
}
.sandbox-card {
position: relative;
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px 16px;
border: 1px solid var(--td-component-stroke);
border-radius: 10px;
background: var(--td-bg-color-container);
transition: border-color 0.18s ease, box-shadow 0.18s ease;
min-width: 0;
&:hover {
border-color: var(--td-brand-color-3, var(--td-brand-color));
box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
}
&--add {
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
min-height: 68px;
border-style: dashed;
background: transparent;
color: var(--td-text-color-placeholder);
cursor: pointer;
font: inherit;
text-align: center;
&:hover,
&:focus-visible {
color: var(--td-brand-color);
border-color: var(--td-brand-color);
box-shadow: none;
}
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
}
&__icon {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
color: var(--td-brand-color);
font-size: 18px;
}
&__label {
font-size: 13px;
font-weight: 500;
line-height: 1.4;
}
}
}
.sandbox-card__badge {
flex-shrink: 0;
width: 36px;
height: 36px;
border-radius: 9px;
display: flex;
align-items: center;
justify-content: center;
margin-top: 1px;
background: rgba(0, 82, 217, 0.1);
color: #0052D9;
}
.sandbox-card--e2b .sandbox-card__badge {
background: rgba(98, 53, 187, 0.1);
color: #6235BB;
}
.sandbox-card--docker .sandbox-card__badge,
.sandbox-card--local .sandbox-card__badge {
background: rgba(17, 128, 83, 0.1);
color: #118053;
}
.sandbox-card__body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
gap: 2px;
}
.sandbox-card__header {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.sandbox-card__title {
flex: 1;
min-width: 0;
margin: 0;
font-size: 14px;
font-weight: 600;
line-height: 1.4;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sandbox-card__subtitle,
.sandbox-card__desc {
margin: 2px 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sandbox-card__desc {
color: var(--td-text-color-placeholder);
}
.sandbox-card__sep {
margin: 0 4px;
color: var(--td-text-color-placeholder);
}
.legacy-tag {
margin-left: 6px;
vertical-align: middle;
}
.sandbox-card__actions {
flex-shrink: 0;
display: flex;
align-items: center;
gap: 2px;
}
.sandbox-card__action-btn {
flex-shrink: 0;
padding: 2px;
opacity: 0;
transition: opacity 0.15s ease;
}
.sandbox-card:hover .sandbox-card__action-btn,
.sandbox-card:focus-within .sandbox-card__action-btn {
opacity: 1;
}
.sandbox-empty-hint {
margin: 16px 0 0;
font-size: 13px;
color: var(--td-text-color-placeholder);
}
.dialog-hint {
margin: 0 0 12px;
font-size: 13px;
color: var(--td-text-color-secondary);
}
.defaults-list {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13px;
}
.defaults-group {
margin-top: 8px;
font-weight: 600;
color: var(--td-text-color-primary);
}
.defaults-label {
display: inline-block;
min-width: 120px;
color: var(--td-text-color-secondary);
}
.inventory {
display: flex;
flex-direction: column;
gap: 12px;
}
</style>

View File

@ -129,6 +129,11 @@
<StorageEngineSettings />
</div>
<!-- 沙箱后端 -->
<div v-if="currentSection === 'sandbox'" class="section">
<SandboxSettings />
</div>
<!-- 系统信息 -->
<div v-if="currentSection === 'system'" class="section">
<SystemInfo />
@ -205,6 +210,7 @@ import ChatHistorySettings from './ChatHistorySettings.vue'
import VectorStoreSettings from './VectorStoreSettings.vue'
import ParserEngineSettings from './ParserEngineSettings.vue'
import StorageEngineSettings from './StorageBackendSettings.vue'
import SandboxSettings from './SandboxSettings.vue'
import WeKnoraCloudSettings from './WeKnoraCloudSettings.vue'
import TenantMembers from './TenantMembers.vue'
import SystemSettings from '@/views/system/SystemSettings.vue'
@ -329,6 +335,7 @@ const navItems = computed(() => {
{ key: 'vectorstore', icon: 'data-base', label: t('settings.vectorStoreEngine') },
{ key: 'parser', icon: 'file-search', label: t('settings.parserEngine') },
{ key: 'storage', icon: 'cloud', label: t('settings.storageEngine') },
{ key: 'sandbox', icon: 'server', label: t('settings.sandbox.title') },
{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
{ key: 'system', icon: 'info-circle', label: t('settings.versionInfo') },
{ key: 'system-global', icon: 'server', label: t('settings.system') },
@ -390,6 +397,7 @@ const navGroups = computed<NavGroup[]>(() => {
'vectorstore',
'parser',
'storage',
'sandbox',
'websearch',
'mcp',
]),

5
go.mod
View File

@ -4,6 +4,7 @@ go 1.26.0
require (
codeberg.org/readeck/go-readability/v2 v2.1.2
connectrpc.com/connect v1.19.1
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.1
github.com/PuerkitoBio/goquery v1.12.0
@ -35,6 +36,7 @@ require (
github.com/larksuite/oapi-sdk-go/v3 v3.9.7
github.com/longbridgeapp/opencc v0.3.13
github.com/mark3labs/mcp-go v0.52.0
github.com/matiasinsaurralde/go-e2b v0.1.1-0.20260808041540-fdc08ceaa1c1
github.com/milvus-io/milvus/client/v2 v2.6.4
github.com/minio/minio-go/v7 v7.1.0
github.com/mmcdole/gofeed v1.3.0
@ -58,12 +60,13 @@ require (
github.com/swaggo/gin-swagger v1.6.1
github.com/swaggo/swag v1.16.6
github.com/tencent/vectordatabase-sdk-go v1.8.4
github.com/tencentcloud/CubeSandbox/sdk/go v0.0.0-20260807115140-5cefcca27a7f
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.103
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap v1.3.103
github.com/tencentyun/cos-go-sdk-v5 v0.7.73
github.com/tiktoken-go/tokenizer v0.7.0
github.com/volcengine/vikingdb-go-sdk v0.0.11
github.com/volcengine/ve-tos-golang-sdk/v2 v2.9.4
github.com/volcengine/vikingdb-go-sdk v0.0.11
github.com/wailsapp/wails/v2 v2.12.0
github.com/weaviate/weaviate v1.37.3
github.com/weaviate/weaviate-go-client/v5 v5.7.3

6
go.sum
View File

@ -1326,6 +1326,8 @@ cloud.google.com/go/workflows v1.12.3/go.mod h1:fmOUeeqEwPzIU81foMjTRQIdwQHADi/v
cloud.google.com/go/workflows v1.12.4/go.mod h1:yQ7HUqOkdJK4duVtMeBCAOPiN1ZF1E9pAMX51vpwB/w=
codeberg.org/readeck/go-readability/v2 v2.1.2 h1:JBrdyYJBRPMBbodLM1b5KxCSDH+JqCkGcuVRD7ICBAw=
codeberg.org/readeck/go-readability/v2 v2.1.2/go.mod h1:Ut31sW4osSrJPR3T8eQslMh4+jbwimXqn0w0ReCT+PU=
connectrpc.com/connect v1.19.1 h1:R5M57z05+90EfEvCY1b7hBxDVOUl45PrtXtAV2fOC14=
connectrpc.com/connect v1.19.1/go.mod h1:tN20fjdGlewnSFeZxLKb0xwIZ6ozc3OQs2hTXy4du9w=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
entgo.io/ent v0.14.3 h1:wokAV/kIlH9TeklJWGGS7AYJdVckr0DloWjIcO9iIIQ=
entgo.io/ent v0.14.3/go.mod h1:aDPE/OziPEu8+OWbzy4UlvWmD2/kbRuWfK2A40hcxJM=
@ -2239,6 +2241,8 @@ github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mark3labs/mcp-go v0.52.0 h1:uRSzupNSUyPGDpF4owY5X4zEpACPwBnlM3FAFuXN6gQ=
github.com/mark3labs/mcp-go v0.52.0/go.mod h1:Zg9cB2HdwdMMVgY0xtTzq3KvYIOJQDsaut+jWjwDaQY=
github.com/matiasinsaurralde/go-e2b v0.1.1-0.20260808041540-fdc08ceaa1c1 h1:iEhD0FOnY0m/7SyTF3vijOXbO++uLNckvD2Ttp87vw0=
github.com/matiasinsaurralde/go-e2b v0.1.1-0.20260808041540-fdc08ceaa1c1/go.mod h1:JTycrO2WcWcZeUNZH6XIk10sV7UixdsGKOt4HQXZiiQ=
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
@ -2614,6 +2618,8 @@ github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
github.com/tencent/vectordatabase-sdk-go v1.8.4 h1:jVATTavFzDypX/TOx+eNrOJk7DcOA0U8REH5NEIC2bs=
github.com/tencent/vectordatabase-sdk-go v1.8.4/go.mod h1:cb53Vbd9Lnh3mA1CwqV9Jy8MrNsxpIUlrhzBiBE7A2M=
github.com/tencentcloud/CubeSandbox/sdk/go v0.0.0-20260807115140-5cefcca27a7f h1:dHvDrWPIE2UPPo1yl8dv+LxBK7lyog3xWfWUlTaXtvI=
github.com/tencentcloud/CubeSandbox/sdk/go v0.0.0-20260807115140-5cefcca27a7f/go.mod h1:4TpzAuDL+yundwIr7UK0N1hVV6L9R/sqcinE+z4W6G0=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.563/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.103 h1:W1dpZ/Q6+DjUpiAUSmIHuFn7rAvetlSqzQCtf0tKEEA=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.3.103/go.mod h1:r5r4xbfxSaeR04b166HGsBa/R4U3SueirEUpXGuw+Q0=

View File

@ -176,6 +176,9 @@ var toolDisplayNames = map[string]string{
agenttools.ToolWebFetch: "获取网页",
agenttools.ToolExecuteSkillScript: "执行技能脚本",
agenttools.ToolReadSkill: "读取技能",
agenttools.ToolListSandboxFiles: "列出沙箱文件",
agenttools.ToolReadSandboxFile: "读取沙箱文件",
agenttools.ToolShellExec: "执行沙箱命令",
}
// toolHintSensitiveArgs lists tools whose arguments should NOT be shown in hints
@ -280,7 +283,7 @@ func (e *AgentEngine) executeToolCallsParallel(
Success: result.Success,
Duration: toolCall.Duration,
Iteration: iteration,
Data: result.Data,
Data: agenttools.SanitizeToolDataForPersist(toolCall.Name, result.Data),
},
})
@ -326,7 +329,7 @@ func (e *AgentEngine) executeSingleToolCall(
Success: result.Success,
Duration: toolCall.Duration,
Iteration: iteration,
Data: result.Data,
Data: agenttools.SanitizeToolDataForPersist(toolCall.Name, result.Data),
},
})
@ -455,16 +458,17 @@ func (e *AgentEngine) runToolCall(
})
principal, _ := types.PrincipalFromContext(ctx)
execTimeout := toolExecutionTimeout(tc.Function.Name)
toolExecCtx := agenttools.WithToolExecContext(toolCtx, &agenttools.ToolExecContext{
SessionID: sessionID,
AssistantMessageID: assistantMessageID,
EventBus: e.eventBus,
ToolCallID: tc.ID,
UserID: principal.StorageID(),
// ApprovalCtx keeps the round-level ctx without the per-tool 60s timeout,
// ApprovalCtx keeps the round-level ctx without the per-tool execution timeout,
// so MCP tool human-approval (issue #1173) can legitimately block longer.
ApprovalCtx: toolCtx,
ExecTimeout: defaultToolExecTimeout,
ExecTimeout: execTimeout,
})
var result *types.ToolResult
@ -475,7 +479,7 @@ func (e *AgentEngine) runToolCall(
// never reach persistence, an external service, or a routing decision.
err = fmt.Errorf("tool arguments contain unresolved model handles: %v", tc.UnresolvedHandles)
} else {
execCtx, toolCancel := context.WithTimeout(toolExecCtx, defaultToolExecTimeout)
execCtx, toolCancel := context.WithTimeout(toolExecCtx, execTimeout)
result, err = e.toolRegistry.ExecuteTool(
execCtx, tc.Function.Name,
json.RawMessage(tc.Function.Arguments),

View File

@ -24,6 +24,10 @@ const (
// defaultToolExecTimeout is the default maximum time for a single tool execution.
// Prevents long-running tools (web_fetch, database_query) from hanging indefinitely.
defaultToolExecTimeout = 60 * time.Second
// shellExecToolTimeout is slightly longer than shell_exec's own hard
// 600-second command timeout so the tool can return a structured timeout
// result instead of being cancelled first by the generic agent wrapper.
shellExecToolTimeout = 10*time.Minute + 5*time.Second
// maxLLMRetries is the maximum number of retries for transient LLM errors.
maxLLMRetries = 2
@ -42,6 +46,13 @@ const (
maxRepeatedResponseRounds = 2
)
func toolExecutionTimeout(toolName string) time.Duration {
if toolName == "shell_exec" {
return shellExecToolTimeout
}
return defaultToolExecTimeout
}
// transientErrorMarkers are substrings that indicate a transient (retryable) error.
var transientErrorMarkers = []string{
"429", "rate limit",

View File

@ -0,0 +1,13 @@
package agent
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestToolExecutionTimeout(t *testing.T) {
assert.Equal(t, 10*time.Minute+5*time.Second, toolExecutionTimeout("shell_exec"))
assert.Equal(t, 60*time.Second, toolExecutionTimeout("web_fetch"))
}

View File

@ -112,6 +112,10 @@ func (e *AgentEngine) systemPromptOptions(ctx context.Context) *BuildSystemPromp
if e.skillsManager != nil && e.skillsManager.IsEnabled() {
opts.SkillsMetadata = e.skillsManager.GetAllMetadata()
}
if e.toolRegistry != nil {
_, err := e.toolRegistry.GetTool(agenttools.ToolShellExec)
opts.ShellExecEnabled = err == nil
}
return opts
}

View File

@ -17,10 +17,22 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
const (
minCurrentTurnToolTokens = 8 * 1024
maxCurrentTurnToolTokens = 32 * 1024
currentTurnToolTokenFraction = 5 // 20%
)
// manageContextWindow consolidates or compresses messages if approaching the token limit.
// currentTokens is the caller's best estimate of the current context size (using
// API-reported Usage when available, falling back to BPE estimation).
func (e *AgentEngine) manageContextWindow(ctx context.Context, messages []chat.Message, round, currentTokens int) []chat.Message {
var trimmed bool
messages, trimmed = trimCurrentTurnToolResults(messages, e.tokenEstimator, currentTurnToolResultBudget(e.config.MaxContextTokens))
if trimmed {
currentTokens = e.tokenEstimator.EstimateMessages(messages)
logger.Infof(ctx, "[Agent][Round-%d] Trimmed current-turn tool results to token budget", round)
}
if e.config.MaxContextTokens <= 0 {
return messages
}
@ -50,6 +62,124 @@ func (e *AgentEngine) manageContextWindow(ctx context.Context, messages []chat.M
return messages
}
func currentTurnToolResultBudget(maxContextTokens int) int {
if maxContextTokens <= 0 {
return maxCurrentTurnToolTokens
}
budget := maxContextTokens / currentTurnToolTokenFraction
if budget < minCurrentTurnToolTokens {
return minCurrentTurnToolTokens
}
if budget > maxCurrentTurnToolTokens {
return maxCurrentTurnToolTokens
}
return budget
}
// trimCurrentTurnToolResults returns a message copy for the next model call.
// It never mutates ToolResult objects used by SSE, diagnostics, or persistence.
// Assistant tool-call messages remain untouched so every compacted tool result
// retains its provider-required call/result pairing.
func trimCurrentTurnToolResults(
messages []chat.Message,
estimator *agenttoken.Estimator,
budget int,
) ([]chat.Message, bool) {
if estimator == nil || budget <= 0 || len(messages) == 0 {
return messages, false
}
lastUser := -1
for i := len(messages) - 1; i >= 0; i-- {
if messages[i].Role == "user" {
lastUser = i
break
}
}
if lastUser < 0 {
return messages, false
}
var toolIndexes []int
total := 0
for i := lastUser + 1; i < len(messages); i++ {
if messages[i].Role == "tool" {
toolIndexes = append(toolIndexes, i)
total += estimator.EstimateMessage(&messages[i])
}
}
if total <= budget || len(toolIndexes) == 0 {
return messages, false
}
out := append([]chat.Message(nil), messages...)
baseCosts := make(map[int]int, len(toolIndexes))
remaining := budget
for _, idx := range toolIndexes {
out[idx].Content = compactedToolResultMarker(messages[idx].Content)
cost := estimator.EstimateMessage(&out[idx])
baseCosts[idx] = cost
remaining -= cost
}
if remaining < 0 {
remaining = 0
}
// Spend the remaining budget newest-first. A result that cannot fit in
// full receives the largest head/tail preview that does fit.
for i := len(toolIndexes) - 1; i >= 0; i-- {
idx := toolIndexes[i]
fullCost := estimator.EstimateMessage(&messages[idx])
extra := fullCost - baseCosts[idx]
if extra <= remaining {
out[idx] = messages[idx]
remaining -= extra
continue
}
out[idx] = compactToolMessage(messages[idx], baseCosts[idx]+remaining, estimator)
remaining = 0
}
return out, true
}
func compactedToolResultMarker(content string) string {
return fmt.Sprintf(
"[Tool result compacted: original_bytes=%d. Re-run the tool with narrower filters or a smaller range if more detail is needed.]",
len(content),
)
}
func compactToolMessage(msg chat.Message, maxTokens int, estimator *agenttoken.Estimator) chat.Message {
runes := []rune(msg.Content)
base := msg
base.Content = compactedToolResultMarker(msg.Content)
if len(runes) == 0 || estimator.EstimateMessage(&base) >= maxTokens {
return base
}
best := base
low, high := 1, len(runes)
for low <= high {
keep := low + (high-low)/2
head := keep / 4
tail := keep - head
candidate := base
candidate.Content = fmt.Sprintf(
"%s\n\n%s\n...[tool result preview omitted]...\n%s",
base.Content,
string(runes[:head]),
string(runes[len(runes)-tail:]),
)
if estimator.EstimateMessage(&candidate) <= maxTokens {
best = candidate
low = keep + 1
} else {
high = keep - 1
}
}
return best
}
// responseVerdict captures the result of analyzing an LLM response to determine
// whether the agent loop should stop and what the final answer is (if any).
type responseVerdict struct {

View File

@ -7,6 +7,7 @@ import (
"testing"
"time"
agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/modelcontext"
"github.com/Tencent/WeKnora/internal/models/chat"
@ -15,6 +16,58 @@ import (
"github.com/stretchr/testify/require"
)
func TestCurrentTurnToolResultBudgetBounds(t *testing.T) {
assert.Equal(t, maxCurrentTurnToolTokens, currentTurnToolResultBudget(0))
assert.Equal(t, minCurrentTurnToolTokens, currentTurnToolResultBudget(10_000))
assert.Equal(t, 20_000, currentTurnToolResultBudget(100_000))
assert.Equal(t, maxCurrentTurnToolTokens, currentTurnToolResultBudget(1_000_000))
}
func TestTrimCurrentTurnToolResultsKeepsNewestAndPairing(t *testing.T) {
estimator, err := agenttoken.NewEstimator()
require.NoError(t, err)
messages := []chat.Message{
{Role: "user", Content: "old turn"},
{Role: "tool", Name: "old", ToolCallID: "old-call", Content: strings.Repeat("historical ", 1000)},
{Role: "assistant", Content: "old answer"},
{Role: "user", Content: "current turn"},
{
Role: "assistant",
ToolCalls: []chat.ToolCall{
{ID: "call-1", Type: "function"},
{ID: "call-2", Type: "function"},
{ID: "call-3", Type: "function"},
},
},
{Role: "tool", Name: "one", ToolCallID: "call-1", Content: strings.Repeat("alpha beta gamma ", 1000)},
{Role: "tool", Name: "two", ToolCallID: "call-2", Content: strings.Repeat("delta epsilon zeta ", 1000)},
{Role: "tool", Name: "three", ToolCallID: "call-3", Content: strings.Repeat("newest result ", 100)},
}
latestCost := estimator.EstimateMessage(&messages[7])
markerOne := messages[5]
markerOne.Content = compactedToolResultMarker(markerOne.Content)
markerTwo := messages[6]
markerTwo.Content = compactedToolResultMarker(markerTwo.Content)
budget := latestCost + estimator.EstimateMessage(&markerOne) + estimator.EstimateMessage(&markerTwo)
trimmed, changed := trimCurrentTurnToolResults(messages, estimator, budget)
require.True(t, changed)
assert.Equal(t, messages[1].Content, trimmed[1].Content, "historical results are handled separately")
assert.Contains(t, trimmed[5].Content, "Tool result compacted")
assert.Contains(t, trimmed[6].Content, "Tool result compacted")
assert.Equal(t, messages[7].Content, trimmed[7].Content, "newest result should be kept in full")
assert.Equal(t, messages[4].ToolCalls, trimmed[4].ToolCalls, "assistant tool-call pairing must remain intact")
assert.Equal(t, strings.Repeat("alpha beta gamma ", 1000), messages[5].Content, "input messages must not be mutated")
total := 0
for _, idx := range []int{5, 6, 7} {
total += estimator.EstimateMessage(&trimmed[idx])
}
assert.LessOrEqual(t, total, budget)
}
// TestAnalyzeResponse_ToolCall_DoesNotTerminate is a regression guard: the
// agent has no dedicated terminal tool — any round that requests tool calls is
// non-terminal and must keep the loop running. The agent ends only by stopping

View File

@ -229,7 +229,7 @@ func renderPromptPlaceholders(template string, knowledgeBases []*KnowledgeBaseIn
// formatSkillsMetadata formats skills metadata for the system prompt (Level 1 - Progressive Disclosure)
// This is a lightweight representation that only includes skill name and description
func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata, shellExecEnabled bool) string {
if len(skillsMetadata) == 0 {
return ""
}
@ -257,7 +257,18 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata) string {
builder.WriteString("- `read_skill(skill_name)`: Load full skill instructions (MUST call before using a skill)\n")
builder.WriteString("- `execute_skill_script(skill_name, script_path, args, input)`: Run utility scripts bundled with a skill\n")
builder.WriteString(" - `input`: Pass data directly via stdin (use this when you have data in memory, e.g. JSON string)\n")
builder.WriteString(" - `args`: Command-line arguments (only use `--file` if you have an actual file path in the skill directory)\n")
builder.WriteString(" - `args`: Command-line arguments; pass absolute `/workspace/input/...` paths from `<sandbox_attachments>` for user-uploaded files\n")
builder.WriteString(" - Treat `/workspace/input` as read-only and write generated files only to `$WEKNORA_SKILL_OUTPUT_DIR`\n")
if shellExecEnabled {
builder.WriteString("- `shell_exec(command, work_dir, timeout_sec, max_output_bytes, max_stderr_bytes, env)`: Freely execute shell commands and explore the current session's isolated Cube sandbox\n")
builder.WriteString(" - User-uploaded files are restored under `/workspace/input` and listed in `<sandbox_attachments>`\n")
builder.WriteString(" - Use `find` and `file` to discover files and types; use `cat`, `head`, `tail`, and `sed` to inspect text; use `grep` and `awk` to search and process content\n")
builder.WriteString(" - Use shell pipelines, redirects, scripts, package managers, compilers, and other installed commands whenever they are the most direct way to complete the task\n")
builder.WriteString(" - Increase `max_output_bytes` up to 65536 per stream for large text output, or use `sed`/`head`/`tail` for targeted sections\n")
builder.WriteString(" - Binary output is suppressed; write binary results under `/workspace/output` so ArtifactCollector attaches them for download\n")
builder.WriteString(" - Session state persists across later `shell_exec` and `execute_skill_script` calls\n")
builder.WriteString(" - Non-zero exit codes are normal results, not tool errors — inspect stderr and decide what to do next\n")
}
return builder.String()
}
@ -295,9 +306,10 @@ func renderPromptPlaceholdersWithStatus(
// BuildSystemPromptOptions contains optional parameters for BuildSystemPrompt
type BuildSystemPromptOptions struct {
SkillsMetadata []*skills.SkillMetadata
Language string // User language name for {{language}} placeholder (e.g. "Chinese (Simplified)")
Config *config.Config // Config for reading prompt templates; nil falls back to hardcoded defaults
SkillsMetadata []*skills.SkillMetadata
ShellExecEnabled bool
Language string // User language name for {{language}} placeholder (e.g. "Chinese (Simplified)")
Config *config.Config // Config for reading prompt templates; nil falls back to hardcoded defaults
}
// BuildSystemPrompt builds the progressive RAG system prompt
@ -346,7 +358,7 @@ func BuildSystemPromptWithOptions(
// Append skills metadata if available (Level 1 - Progressive Disclosure)
if options != nil && len(options.SkillsMetadata) > 0 {
basePrompt += formatSkillsMetadata(options.SkillsMetadata)
basePrompt += formatSkillsMetadata(options.SkillsMetadata, options.ShellExecEnabled)
}
return basePrompt

View File

@ -0,0 +1,24 @@
package agent
import (
"testing"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFormatSkillsMetadataIncludesShellGuidanceOnlyWhenEnabled(t *testing.T) {
metadata := []*skills.SkillMetadata{{Name: "demo", Description: "demo skill"}}
enabled := formatSkillsMetadata(metadata, true)
require.Contains(t, enabled, "shell_exec")
for _, command := range []string{"find", "file", "cat", "head", "tail", "sed", "grep", "awk"} {
assert.Contains(t, enabled, command)
}
assert.Contains(t, enabled, "Freely execute shell commands")
assert.Contains(t, enabled, "Binary output is suppressed")
disabled := formatSkillsMetadata(metadata, false)
assert.NotContains(t, disabled, "shell_exec")
}

View File

@ -3,11 +3,67 @@ package skills
import (
"context"
"fmt"
"os"
"path"
"strings"
"sync"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// artifactOutputEnvVar is the name of the environment variable that WeKnora
// injects into every skill script execution. The value points to the
// convention-driven directory where the script should drop artifacts the user
// will be able to download after the turn completes.
//
// The name is stable across releases; skills reference it via os.getenv(...)
// so they never hard-code the path.
const artifactOutputEnvVar = "WEKNORA_SKILL_OUTPUT_DIR"
// sessionInputEnvVar points skill scripts at user-uploaded files restored into
// the current session's Cube. Inputs are separate from generated artifacts.
const sessionInputEnvVar = "WEKNORA_SESSION_INPUT_DIR"
// artifactHistoryEnvVar is the name of the environment variable that points
// to the root artifact output directory (/workspace/output). Skill scripts
// can use this to self-discover artifacts from prior runs when they need to
// chain without LLM mediation.
const artifactHistoryEnvVar = "WEKNORA_SKILL_HISTORY_ROOT"
// defaultArtifactOutputDir is used when neither the environment variable
// (WEKNORA_SKILL_OUTPUT_DIR) nor the ExecuteConfig.Env has an override.
// /workspace/output sits inside the base sandbox image's writable tree and
// is guaranteed to survive across Execute calls for the same session (Cube
// SessionBoundManager keeps the MicroVM alive between calls).
const defaultArtifactOutputDir = "/workspace/output"
// ArtifactOutputDir returns the absolute path (inside the sandbox) where
// skill scripts should write artifacts for this turn. It is exported so
// callers such as ArtifactCollector can list the same directory when
// draining artifacts after Execute returns.
//
// Resolution order (first non-empty wins):
// 1. WEKNORA_SKILL_OUTPUT_DIR from the host environment (ops override).
// 2. defaultArtifactOutputDir.
//
// Callers are expected to treat the returned string as read-only: the path
// is normalised (no trailing slash) so it can be joined safely.
func ArtifactOutputDir() string {
if v := strings.TrimSpace(os.Getenv(artifactOutputEnvVar)); v != "" {
return path.Clean(v)
}
return defaultArtifactOutputDir
}
// SkillOutputDir returns the artifact output directory for skill executions.
// All skills write to the same root directory (/workspace/output/) to enable
// collaboration and file sharing between different skill executions.
func (m *Manager) SkillOutputDir(sessionID, skillName string) string {
return ArtifactOutputDir()
}
// Manager manages skills lifecycle including discovery, loading, and script execution
// It coordinates between the Loader (filesystem operations) and Sandbox (script execution)
type Manager struct {
@ -203,17 +259,58 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin
}
// Prepare execution config
logger.Info(ctx, "[Tool][ExecuteScript]:Prepare execution config")
sessionID, _ := types.SessionIDFromContext(ctx)
// Compute the artifact output directory. All skills share the same root
// directory (/workspace/output/) to enable collaboration and file sharing
// between different skill executions in the same session.
// Skill scripts read the directory via WEKNORA_SKILL_OUTPUT_DIR; the
// root (for cross-run discovery) is available via WEKNORA_SKILL_HISTORY_ROOT.
outputDir := m.SkillOutputDir(sessionID, skillName)
env := map[string]string{
artifactOutputEnvVar: outputDir,
artifactHistoryEnvVar: ArtifactOutputDir(),
}
// SessionFileStore advertises the "sandbox provides per-session file
// storage" capability. When present we can safely expose the input
// staging directory and pre-materialise the output directory; when
// absent (Local/Docker or fallback), stateless backends materialise
// directories on their own during script execution.
fileStore := sessionFileStoreFromManager(m.sandboxMgr)
if fileStore != nil {
env[sessionInputEnvVar] = sandbox.SessionInputRoot
if sessionID != "" {
if err := fileStore.EnsureSessionDir(ctx, sessionID, outputDir); err != nil {
logger.Warnf(ctx, "[Tool][ExecuteScript] pre-create output dir %s failed: %v", outputDir, err)
}
}
}
config := &sandbox.ExecuteConfig{
Script: file.Path,
Args: args,
WorkDir: basePath,
Stdin: stdin,
Script: file.Path,
Args: args,
WorkDir: basePath,
Stdin: stdin,
Env: env,
SessionID: sessionID,
}
// Execute in sandbox
return m.sandboxMgr.Execute(ctx, config)
}
// sessionFileStoreFromManager returns the sandbox manager's effective
// session filesystem capability, or nil when the backend cannot expose one.
// Isolated in a helper so callers stay free of provider-specific branches.
func sessionFileStoreFromManager(mgr sandbox.Manager) sandbox.SessionFileStore {
provider, ok := mgr.(sandbox.SessionCapabilityProvider)
if !ok || provider == nil {
return nil
}
return provider.SessionFileStore()
}
// GetSkillInfo returns detailed information about a skill
func (m *Manager) GetSkillInfo(ctx context.Context, skillName string) (*SkillInfo, error) {
if !m.enabled {

View File

@ -21,6 +21,19 @@ const (
// Skills-related tools (only available when skills are enabled)
ToolExecuteSkillScript = "execute_skill_script"
ToolReadSkill = "read_skill"
// Sandbox filesystem inspection (read-only; only available when the
// sandbox backend supports per-session file listing — currently the
// Cube SessionBoundManager). Lets the LLM discover and inspect files
// produced by prior skill executions in the same session so chained
// skills stop guessing paths.
ToolListSandboxFiles = "list_sandbox_files"
ToolReadSandboxFile = "read_sandbox_file"
// ToolShellExec lets the LLM execute ad-hoc shell commands inside the
// current session's Cube sandbox (dependency installs, environment
// probing). Only registered when the sandbox backend is Cube — Docker
// and Local backends do not expose this tool to preserve their
// existing stateless security model.
ToolShellExec = "shell_exec"
// Wiki-related tools (only available when wiki KBs are in scope)
ToolWikiReadPage = "wiki_read_page"
ToolWikiWritePage = "wiki_write_page"
@ -57,6 +70,9 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
{Name: ToolListSandboxFiles, Label: "列出沙箱文件", Description: "列出当前会话沙箱产出目录下的文件"},
{Name: ToolReadSandboxFile, Label: "读取沙箱文件", Description: "读取当前会话沙箱中已生成的文件内容"},
{Name: ToolShellExec, Label: "执行沙箱命令", Description: "在当前会话沙箱中执行 shell 命令(如安装依赖、检查环境)"},
{Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},
{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
{Name: ToolWikiReadSourceDoc, Label: "精读源文档", Description: "使用知识点深入阅读特定原始文档"},

View File

@ -13,6 +13,13 @@ var persistStripFields = map[string][]string{
"grep_results": {"chunk_results"},
}
var persistStripFieldsByTool = map[string][]string{
ToolShellExec: {"stdout", "stderr", "content", "content_base64"},
ToolReadSandboxFile: {"stdout", "stderr", "content", "content_base64"},
}
const historicalSandboxOutputChars = 4 * 1024
// ShouldOmitRawToolOutput reports whether the raw XML/text Output should be
// excluded from SSE replay and persisted agent_steps. The full Output remains
// available in-memory for the current agent turn.
@ -25,7 +32,7 @@ func ShouldOmitRawToolOutput(_ string, data map[string]interface{}) bool {
}
// SanitizeToolDataForPersist returns a copy of tool Data safe for DB / SSE replay.
func SanitizeToolDataForPersist(data map[string]interface{}) map[string]interface{} {
func SanitizeToolDataForPersist(toolName string, data map[string]interface{}) map[string]interface{} {
if data == nil {
return nil
}
@ -37,17 +44,20 @@ func SanitizeToolDataForPersist(data map[string]interface{}) map[string]interfac
for _, key := range persistStripFields[displayType] {
delete(out, key)
}
for _, key := range persistStripFieldsByTool[toolName] {
delete(out, key)
}
return out
}
// SanitizeToolResultForClient builds stream / persistence metadata for the UI.
func SanitizeToolResultForClient(_ string, result *types.ToolResult) map[string]interface{} {
func SanitizeToolResultForClient(toolName string, result *types.ToolResult) map[string]interface{} {
meta := map[string]interface{}{}
if result == nil {
return meta
}
if result.Data != nil {
for k, v := range SanitizeToolDataForPersist(result.Data) {
for k, v := range SanitizeToolDataForPersist(toolName, result.Data) {
meta[k] = v
}
}
@ -88,8 +98,10 @@ func SanitizeAgentStepsForStorage(steps []types.AgentStep) []types.AgentStep {
result := *tc.Result
if ShouldOmitRawToolOutput(tc.Name, result.Data) {
result.Output = compactToolSummary(result.Success, result.Error, result.Data)
result.Data = SanitizeToolDataForPersist(result.Data)
} else if isSandboxContentTool(tc.Name) {
result.Output = compactHistoricalSandboxOutput(result.Output)
}
result.Data = SanitizeToolDataForPersist(tc.Name, result.Data)
toolCalls[j].Result = &result
}
out[i].ToolCalls = toolCalls
@ -109,11 +121,29 @@ func CompactToolOutputForHistory(toolName string, result *types.ToolResult) stri
return "Error: tool call failed"
}
if result.Output != "" && !ShouldOmitRawToolOutput(toolName, result.Data) {
if isSandboxContentTool(toolName) {
return compactHistoricalSandboxOutput(result.Output)
}
return result.Output
}
return compactToolSummary(result.Success, result.Error, result.Data)
}
func isSandboxContentTool(toolName string) bool {
return toolName == ToolShellExec || toolName == ToolReadSandboxFile
}
func compactHistoricalSandboxOutput(output string) string {
if len(output) <= historicalSandboxOutputChars {
return output
}
const marker = "\n...[historical tool output compacted]...\n"
kept := historicalSandboxOutputChars - len(marker)
head := kept / 4
tail := kept - head
return output[:head] + marker + output[len(output)-tail:]
}
func compactToolSummary(success bool, errMsg string, data map[string]interface{}) string {
if !success {
if errMsg != "" {

View File

@ -27,7 +27,7 @@ func TestSanitizeToolDataForPersist_knowledgeChunksList(t *testing.T) {
"total_chunks": 282,
"chunks": []map[string]interface{}{{"content": "secret"}},
}
out := SanitizeToolDataForPersist(data)
out := SanitizeToolDataForPersist(ToolListKnowledgeChunks, data)
if _, ok := out["chunks"]; ok {
t.Fatal("chunk bodies should be stripped from persisted tool data")
}
@ -87,3 +87,43 @@ func TestSanitizeToolResultForClient_omitsOutput(t *testing.T) {
t.Fatalf("summary metadata should remain, got %#v", meta["fetched_chunks"])
}
}
func TestSandboxToolPersistenceStripsDuplicatePayloadsAndCompactsHistory(t *testing.T) {
rawOutput := strings.Repeat("shell output ", 1000)
steps := []types.AgentStep{{
ToolCalls: []types.ToolCall{{
Name: ToolShellExec,
Result: &types.ToolResult{
Success: true,
Output: rawOutput,
Data: map[string]interface{}{
"stdout": strings.Repeat("x", 10000),
"stderr": strings.Repeat("y", 10000),
"content": strings.Repeat("z", 10000),
"content_base64": strings.Repeat("A", 10000),
"exit_code": 0,
"stdout_original_bytes": 10000,
"stdout_truncated": true,
},
},
}},
}}
sanitized := SanitizeAgentStepsForStorage(steps)
result := sanitized[0].ToolCalls[0].Result
assert := func(condition bool, message string) {
t.Helper()
if !condition {
t.Fatal(message)
}
}
assert(len(result.Output) <= historicalSandboxOutputChars, "persisted shell output must be capped")
for _, key := range []string{"stdout", "stderr", "content", "content_base64"} {
_, exists := result.Data[key]
assert(!exists, key+" should be stripped")
}
assert(result.Data["exit_code"] == 0, "exit metadata should remain")
assert(len(CompactToolOutputForHistory(ToolShellExec, steps[0].ToolCalls[0].Result)) <= historicalSandboxOutputChars,
"historical replay must independently cap legacy raw output")
}

View File

@ -21,6 +21,13 @@ type ToolRegistry struct {
maxToolOutputSize int // maximum chars for tool output (0 = use DefaultMaxToolOutput)
}
// outputLimitProvider is implemented by tools that expose a caller-configurable
// output budget with their own hard safety cap. It prevents the registry's
// generic limit from undoing that explicit bounded choice.
type outputLimitProvider interface {
OutputLimitChars(args json.RawMessage) int
}
// NewToolRegistry creates a new tool registry
func NewToolRegistry() *ToolRegistry {
return &ToolRegistry{
@ -144,6 +151,11 @@ func (r *ToolRegistry) ExecuteTool(
// Publish the ceiling so budget-aware tools can shape a batched result
// themselves; the truncation below stays as the fallback for the rest.
maxOutput := r.getMaxToolOutput()
if provider, ok := tool.(outputLimitProvider); ok {
if toolLimit := provider.OutputLimitChars(args); toolLimit > maxOutput {
maxOutput = toolLimit
}
}
result, execErr := tool.Execute(WithOutputBudget(ctx, maxOutput), args)
// Truncate large tool outputs to prevent context window poisoning. The

View File

@ -0,0 +1,298 @@
// Package tools — list_sandbox_files.
//
// Read-only tool that lets the LLM enumerate files under a session's
// sandbox artifact output directory. Without this tool, the LLM cannot
// see files produced by prior skill invocations in the same session and
// has to guess paths when chaining skills together.
//
// Design notes:
// - Session-scoped: the sandbox path is resolved from the tool exec
// context (`ToolExecContext.SessionID`). The LLM cannot pass an
// arbitrary session ID.
// - Directory guardrail: `path` must resolve underneath the session's
// artifact output dir (`$WEKNORA_SKILL_OUTPUT_DIR`, default
// `/workspace/output`). This keeps the tool aligned with the
// directory ArtifactCollector already drains so anything the LLM
// lists is guaranteed to also become a downloadable artifact.
// - Read-only: this tool never creates, modifies or deletes anything
// inside the sandbox. Writes still go through skill scripts.
// - Graceful "no sandbox": if the session has never spawned a sandbox
// yet (chat-only turn, or sandbox was reaped), the tool returns an
// empty listing with a helpful message rather than an error, so the
// LLM can decide to invoke a skill first.
package tools
import (
"context"
"encoding/json"
"fmt"
"path"
"sort"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// SandboxFileSource is the narrow, tool-facing subset of a session-aware
// sandbox manager. In production it is satisfied by
// *sandbox.SessionBoundManager; tests can stub it with an in-memory fake.
//
// Keeping the interface local to the tools package avoids leaking a
// dependency on internal/application/service (which is a higher layer)
// and mirrors the pattern used by ArtifactCollector.SandboxArtifactSource.
type SandboxFileSource interface {
ListSessionFiles(ctx context.Context, sessionID, dir string) ([]sandbox.RemoteDirEntry, error)
StatSessionFile(ctx context.Context, sessionID, path string) (*sandbox.RemoteStatEntry, error)
ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
}
// defaultListSandboxMaxEntries caps a single list_sandbox_files call at
// this many entries so a runaway directory can't blow up the LLM context.
// Aligns with the "sane pagination" advice in the Anthropic tool-use guide.
const (
defaultListSandboxMaxEntries = 200
maxListSandboxMaxEntries = 500
)
// Tool schema
var listSandboxFilesTool = BaseTool{
name: ToolListSandboxFiles,
description: `List files produced by prior skill executions in the current session's sandbox.
## Usage
- Call this tool BEFORE invoking a follow-up skill that consumes a file
produced by an earlier skill in this session. Without this tool you are
guessing paths; with it you can see exactly what is available.
- Also useful to confirm a skill actually produced the files it claims to
have generated (e.g. before telling the user "your report is ready").
## When to Use
- The user asks a follow-up question that references a file from a prior
turn ("summarize the report you generated", "improve the chart").
- You are about to chain two skills where the second consumes an output
of the first.
- You want to give the user a listing of everything the current session
has produced.
## Path Rules
- ` + "`path`" + ` is optional. When omitted, the tool lists the default artifact
output directory (` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `).
- When provided, ` + "`path`" + ` MUST be underneath the artifact output directory.
Attempts to list arbitrary sandbox paths (e.g. ` + "`/etc`" + `, ` + "`/home`" + `) are
rejected.
- Listing is recursive: sub-directories are traversed automatically and
only files are returned in the flat listing.
## Returns
- A list of entries with ` + "`path`" + ` (absolute, ready to pass to
` + "`read_sandbox_file`" + `), ` + "`size`" + `, and ` + "`modified_at`" + ` timestamps.
- When the session has never invoked a skill (no live sandbox yet), the
tool returns an empty listing with a clear "no sandbox" note — this is
not an error.`,
schema: utils.GenerateSchema[ListSandboxFilesInput](),
}
// ListSandboxFilesInput defines the input parameters for list_sandbox_files.
type ListSandboxFilesInput struct {
// Path is the absolute path inside the sandbox to list. When empty
// the tool falls back to skills.ArtifactOutputDir(). Must be
// underneath the artifact output directory.
Path string `json:"path,omitempty" jsonschema:"Optional absolute sandbox path to list. Defaults to the session's artifact output directory. Must be underneath that directory."`
// MaxEntries caps the listing size to protect the LLM context.
// Zero uses defaultListSandboxMaxEntries.
MaxEntries int `json:"max_entries,omitempty" jsonschema:"Optional cap on the number of entries returned. Defaults to 200, hard-capped at 500. Use a smaller value when you only need to check whether a specific file exists."`
}
// ListSandboxFilesTool exposes SandboxFileSource.ListSessionFiles to the
// agent as a read-only enumeration primitive.
type ListSandboxFilesTool struct {
BaseTool
source SandboxFileSource
}
// NewListSandboxFilesTool constructs the tool. `source` MUST NOT be nil:
// callers should feature-gate registration in the agent bootstrap when
// the sandbox backend does not support per-session file inspection.
func NewListSandboxFilesTool(source SandboxFileSource) *ListSandboxFilesTool {
return &ListSandboxFilesTool{
BaseTool: listSandboxFilesTool,
source: source,
}
}
// Execute enumerates files under the requested path inside the current
// session's sandbox.
func (t *ListSandboxFilesTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][ListSandboxFiles] Execute started")
var input ListSandboxFilesInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, nil
}
if t.source == nil {
return &types.ToolResult{
Success: false,
Error: "sandbox file inspection is not available in this deployment",
}, nil
}
// Resolve session ID from tool exec context (preferred) or the
// ambient context helper (fallback for direct unit tests).
sessionID := resolveSessionID(ctx)
if sessionID == "" {
return &types.ToolResult{
Success: false,
Error: "no session ID in context; list_sandbox_files must run inside an agent turn",
}, nil
}
// Resolve target directory. When the caller omits path we scan the
// same directory ArtifactCollector drains, guaranteeing everything
// the LLM sees will also be downloadable.
rootDir := skills.ArtifactOutputDir()
targetDir := strings.TrimSpace(input.Path)
if targetDir == "" {
targetDir = rootDir
} else {
clean := path.Clean(targetDir)
if !isUnderRoot(clean, rootDir) {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"path %q is outside the artifact output directory %q; the LLM can only list files under the artifact output directory",
input.Path, rootDir,
),
}, nil
}
targetDir = clean
}
maxEntries := input.MaxEntries
if maxEntries <= 0 {
maxEntries = defaultListSandboxMaxEntries
}
if maxEntries > maxListSandboxMaxEntries {
maxEntries = maxListSandboxMaxEntries
}
entries, err := t.source.ListSessionFiles(ctx, sessionID, targetDir)
if err != nil {
logger.Warnf(ctx, "[Tool][ListSandboxFiles] list failed: session=%s dir=%s err=%v",
sessionID, targetDir, err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("failed to list %s: %v", targetDir, err),
}, nil
}
// Deterministic ordering by path so multiple calls return the same
// pagination window even when the underlying backend does not
// guarantee ordering.
sort.SliceStable(entries, func(i, j int) bool {
return entries[i].Path < entries[j].Path
})
truncated := false
if len(entries) > maxEntries {
entries = entries[:maxEntries]
truncated = true
}
// Build human-readable output for the LLM. Machine-consumable data
// goes into ToolResult.Data.
var b strings.Builder
b.WriteString(fmt.Sprintf("=== Sandbox listing: %s ===\n\n", targetDir))
if len(entries) == 0 {
b.WriteString("No files found. Either no skill has produced output in this session yet, or the sandbox has been reaped.\n")
} else {
b.WriteString(fmt.Sprintf("Found %d file(s)", len(entries)))
if truncated {
b.WriteString(fmt.Sprintf(" (truncated to %d; increase max_entries to see more)", maxEntries))
}
b.WriteString(":\n\n")
for _, e := range entries {
b.WriteString(fmt.Sprintf("- %s (size=%d, modified=%s)\n",
e.Path, e.Size, formatSandboxModTime(e.ModTime)))
}
}
// Serialise entries for structured consumption.
items := make([]map[string]interface{}, 0, len(entries))
for _, e := range entries {
items = append(items, map[string]interface{}{
"name": e.Name,
"path": e.Path,
"size": e.Size,
"modified_at": formatSandboxModTime(e.ModTime),
})
}
logger.Infof(ctx, "[Tool][ListSandboxFiles] session=%s dir=%s count=%d truncated=%v",
sessionID, targetDir, len(items), truncated)
return &types.ToolResult{
Success: true,
Output: b.String(),
Data: map[string]interface{}{
"session_id": sessionID,
"path": targetDir,
"root": rootDir,
"entries": items,
"count": len(items),
"truncated": truncated,
},
}, nil
}
// Cleanup releases any resources.
func (t *ListSandboxFilesTool) Cleanup(ctx context.Context) error {
return nil
}
// formatSandboxModTime renders a mod time in the RFC3339 shape the tool has
// historically emitted. Zero times render as the empty string so LLM output
// stays visually clean.
func formatSandboxModTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(time.RFC3339)
}
// resolveSessionID pulls the session ID out of the tool exec context (set
// by the agent engine per tool call) with a fallback to the ambient
// context helper used elsewhere in WeKnora.
func resolveSessionID(ctx context.Context) string {
if meta, ok := ToolExecFromContext(ctx); ok && meta != nil && meta.SessionID != "" {
return meta.SessionID
}
if sid, ok := types.SessionIDFromContext(ctx); ok {
return sid
}
return ""
}
// isUnderRoot reports whether clean sits at or underneath root. Both
// arguments must already be cleaned. This guardrail keeps the LLM from
// listing paths outside the artifact output directory: even if a rogue
// prompt asks for `/etc/passwd`, the tool refuses.
func isUnderRoot(clean, root string) bool {
if clean == root {
return true
}
rootWithSep := root
if !strings.HasSuffix(rootWithSep, "/") {
rootWithSep += "/"
}
return strings.HasPrefix(clean, rootWithSep)
}

View File

@ -0,0 +1,282 @@
// Package tools — read_sandbox_file.
//
// Read-only tool that lets the LLM read the contents of a file the
// current session's sandbox has produced. Pairs with list_sandbox_files:
// the LLM lists first, then reads a specific path.
//
// Design notes:
// - Session-scoped: path must belong to the current session's sandbox,
// enforced by delegating to SandboxFileSource.ReadSessionFile which
// itself takes the session ID from context.
// - Directory guardrail: path must sit underneath the artifact output
// directory. This makes the tool a companion to ArtifactCollector,
// not a general-purpose filesystem reader (skills that need to peek
// elsewhere should print via stdout).
// - Stat-first size cap: files over 64 KiB are never downloaded. The
// model receives metadata and uses shell_exec with sed/head/tail/grep/awk
// to inspect only the relevant text section.
// - Binary handling: binary bytes are never returned or base64-encoded into
// model/client data. ArtifactCollector remains the download path.
package tools
import (
"context"
"encoding/json"
"fmt"
"path"
"strings"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// A read larger than this is refused before ReadSessionFile is called. The
// caller may request a smaller ceiling, but never raise this hard limit.
const (
defaultReadSandboxMaxBytes int64 = 64 * 1024
maxReadSandboxMaxBytes int64 = 64 * 1024
)
// Tool schema
var readSandboxFileTool = BaseTool{
name: ToolReadSandboxFile,
description: `Read the contents of a file the current session's sandbox has produced.
## Usage
- Use in tandem with ` + "`list_sandbox_files`" + `: first list to find the file,
then read to inspect its content.
- Handy when the user asks "what did that report say?" or you want to
quote a section of a skill-generated artifact.
## When to Use
- After a skill claims it wrote something and you want to confirm the
content matches expectations.
- Before invoking a follow-up skill that consumes a file — you may want
to inspect a snippet to decide which skill to invoke or what arguments
to pass.
- When the user asks you to summarise or edit a previously generated
artifact.
## Path Rules
- ` + "`path`" + ` MUST be an absolute path returned by ` + "`list_sandbox_files`" + `.
- ` + "`path`" + ` MUST sit underneath the session's artifact output directory
(` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `). Reads
outside that directory are rejected.
## Size Handling
- Files larger than 64 KiB are NOT downloaded or returned.
- For large text, use ` + "`shell_exec`" + ` with ` + "`sed -n`" + `, ` + "`head`" + `,
` + "`tail`" + `, ` + "`grep`" + `, or ` + "`awk`" + ` to inspect a targeted section.
- ` + "`max_bytes`" + ` may lower the refusal threshold but cannot exceed 65536.
## Binary Files
- Binary bytes are never returned to the model or embedded as base64.
- Use the ArtifactCollector download attachment for PDFs, PPTX files, images,
archives, and other binary artifacts.`,
schema: utils.GenerateSchema[ReadSandboxFileInput](),
}
// ReadSandboxFileInput defines the input parameters for read_sandbox_file.
type ReadSandboxFileInput struct {
// Path is the absolute path inside the sandbox to read. Required.
// Must sit underneath the artifact output directory.
Path string `json:"path" jsonschema:"Absolute path inside the sandbox. Must sit under the session's artifact output directory (typically /workspace/output). Get valid paths from list_sandbox_files."`
// MaxBytes is the largest file the tool may download. Zero uses 64 KiB;
// callers may lower but never raise the hard 64 KiB ceiling.
MaxBytes int64 `json:"max_bytes,omitempty" jsonschema:"Optional maximum file size to read. Defaults to 65536 bytes and is hard-capped at 65536. Larger files are not downloaded; use shell_exec with sed/head/tail/grep/awk."`
}
// ReadSandboxFileTool exposes SandboxFileSource.ReadSessionFile as a
// safe, session-scoped read primitive.
type ReadSandboxFileTool struct {
BaseTool
source SandboxFileSource
}
// NewReadSandboxFileTool constructs the tool. `source` MUST NOT be nil:
// callers should feature-gate registration when the sandbox backend
// does not support per-session file inspection.
func NewReadSandboxFileTool(source SandboxFileSource) *ReadSandboxFileTool {
return &ReadSandboxFileTool{
BaseTool: readSandboxFileTool,
source: source,
}
}
// Execute reads the requested file (bounded by size cap) from the
// current session's sandbox.
func (t *ReadSandboxFileTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][ReadSandboxFile] Execute started")
var input ReadSandboxFileInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, nil
}
if t.source == nil {
return &types.ToolResult{
Success: false,
Error: "sandbox file inspection is not available in this deployment",
}, nil
}
trimmed := strings.TrimSpace(input.Path)
if trimmed == "" {
return &types.ToolResult{
Success: false,
Error: "path is required; call list_sandbox_files first to discover valid paths",
}, nil
}
sessionID := resolveSessionID(ctx)
if sessionID == "" {
return &types.ToolResult{
Success: false,
Error: "no session ID in context; read_sandbox_file must run inside an agent turn",
}, nil
}
// Enforce that the path sits underneath the artifact output dir.
// This mirrors list_sandbox_files' rule so the LLM sees a
// consistent "reachable surface".
rootDir := skills.ArtifactOutputDir()
clean := path.Clean(trimmed)
if !isUnderRoot(clean, rootDir) {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"path %q is outside the artifact output directory %q; only files produced under that directory can be read",
input.Path, rootDir,
),
}, nil
}
// Resolve the byte cap for this call.
maxBytes := input.MaxBytes
if maxBytes <= 0 {
maxBytes = defaultReadSandboxMaxBytes
}
if maxBytes > maxReadSandboxMaxBytes {
maxBytes = maxReadSandboxMaxBytes
}
stat, err := t.source.StatSessionFile(ctx, sessionID, clean)
if err != nil {
logger.Warnf(ctx, "[Tool][ReadSandboxFile] stat failed: session=%s path=%s err=%v",
sessionID, clean, err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("failed to inspect %s before reading: %v", clean, err),
}, nil
}
if stat == nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("file not found: %s", clean),
}, nil
}
if stat.Type == sandbox.RemoteEntryDir {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("path is a directory, not a file: %s", clean),
}, nil
}
if stat.Size > maxBytes {
logger.Infof(ctx, "[Tool][ReadSandboxFile] refused oversize file: session=%s path=%s size=%d limit=%d",
sessionID, clean, stat.Size, maxBytes)
return oversizedSandboxFileResult(sessionID, clean, rootDir, stat.Size, maxBytes), nil
}
data, err := t.source.ReadSessionFile(ctx, sessionID, clean)
if err != nil {
logger.Warnf(ctx, "[Tool][ReadSandboxFile] read failed: session=%s path=%s err=%v",
sessionID, clean, err)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("failed to read %s: %v", clean, err),
}, nil
}
total := int64(len(data))
// The file may have grown between Stat and Read. Do not return a prefix
// from a full oversized download as if it were an intentional partial read.
if total > maxBytes {
logger.Warnf(ctx, "[Tool][ReadSandboxFile] file grew during read: session=%s path=%s size=%d limit=%d",
sessionID, clean, total, maxBytes)
return oversizedSandboxFileResult(sessionID, clean, rootDir, total, maxBytes), nil
}
binary := isBinaryShellOutput(string(data))
// Build LLM-facing output. Text is inlined only once in Output; binary
// bytes are suppressed and represented by metadata.
var b strings.Builder
b.WriteString(fmt.Sprintf("=== Sandbox file: %s ===\n\n", clean))
b.WriteString(fmt.Sprintf("size=%d bytes, returned=%d bytes\n", total, len(data)))
resultData := map[string]interface{}{
"session_id": sessionID,
"path": clean,
"root": rootDir,
"size": total,
"returned_bytes": len(data),
"truncated": false,
"binary": binary,
}
if binary {
b.WriteString("binary file — content suppressed; use the artifact attachment to download it.\n")
} else {
b.WriteString("\n```\n")
b.Write(data)
if len(data) > 0 && data[len(data)-1] != '\n' {
b.WriteString("\n")
}
b.WriteString("```\n")
}
logger.Infof(ctx, "[Tool][ReadSandboxFile] session=%s path=%s size=%d returned=%d binary=%v",
sessionID, clean, total, len(data), binary)
return &types.ToolResult{
Success: true,
Output: b.String(),
Data: resultData,
}, nil
}
func oversizedSandboxFileResult(sessionID, filePath, rootDir string, size, limit int64) *types.ToolResult {
output := fmt.Sprintf(
"=== Sandbox file too large to read: %s ===\n\n"+
"size=%d bytes, limit=%d bytes, returned=0 bytes\n\n"+
"The file was not downloaded. Use shell_exec with sed -n, head, tail, grep, or awk "+
"to inspect only the relevant text section. Binary files remain available through the artifact attachment.\n",
filePath, size, limit,
)
return &types.ToolResult{
Success: true,
Output: output,
Data: map[string]interface{}{
"session_id": sessionID,
"path": filePath,
"root": rootDir,
"size": size,
"limit": limit,
"returned_bytes": 0,
"truncated": true,
"read_refused": true,
},
}
}
// Cleanup releases any resources.
func (t *ReadSandboxFileTool) Cleanup(ctx context.Context) error {
return nil
}

View File

@ -0,0 +1,125 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type fakeSandboxFileSource struct {
stat *sandbox.RemoteStatEntry
statErr error
data []byte
readErr error
entries []sandbox.RemoteDirEntry
statCalls int
readCalls int
}
func (f *fakeSandboxFileSource) ListSessionFiles(context.Context, string, string) ([]sandbox.RemoteDirEntry, error) {
return f.entries, nil
}
func (f *fakeSandboxFileSource) StatSessionFile(context.Context, string, string) (*sandbox.RemoteStatEntry, error) {
f.statCalls++
return f.stat, f.statErr
}
func (f *fakeSandboxFileSource) ReadSessionFile(context.Context, string, string) ([]byte, error) {
f.readCalls++
return f.data, f.readErr
}
func sandboxFileTestContext() context.Context {
return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "session-1"})
}
func TestReadSandboxFileRefusesOversizeBeforeRead(t *testing.T) {
source := &fakeSandboxFileSource{
stat: &sandbox.RemoteStatEntry{Path: "/workspace/output/large.txt", Type: sandbox.RemoteEntryFile, Size: maxReadSandboxMaxBytes + 1},
data: []byte("must not be read"),
}
result, err := NewReadSandboxFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/workspace/output/large.txt","max_bytes":999999}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, 1, source.statCalls)
assert.Zero(t, source.readCalls)
assert.Equal(t, true, result.Data["read_refused"])
assert.Equal(t, int64(maxReadSandboxMaxBytes+1), result.Data["size"])
assert.Contains(t, result.Output, "shell_exec")
}
func TestReadSandboxFileReturnsSmallTextOnlyInOutput(t *testing.T) {
content := []byte("hello sandbox\n")
source := &fakeSandboxFileSource{
stat: &sandbox.RemoteStatEntry{Path: "/workspace/output/report.txt", Type: sandbox.RemoteEntryFile, Size: int64(len(content))},
data: content,
}
result, err := NewReadSandboxFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/workspace/output/report.txt"}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, 1, source.readCalls)
assert.Contains(t, result.Output, string(content))
_, duplicated := result.Data["content"]
assert.False(t, duplicated)
}
func TestReadSandboxFileSuppressesBinaryWithoutBase64(t *testing.T) {
content := []byte{0xff, 0x00, 0x01}
source := &fakeSandboxFileSource{
stat: &sandbox.RemoteStatEntry{Path: "/workspace/output/image.bin", Type: sandbox.RemoteEntryFile, Size: int64(len(content))},
data: content,
}
result, err := NewReadSandboxFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/workspace/output/image.bin"}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, true, result.Data["binary"])
assert.NotContains(t, result.Output, string(content))
assert.Contains(t, result.Output, "content suppressed")
_, hasBase64 := result.Data["content_base64"]
assert.False(t, hasBase64)
}
func TestListSandboxFilesHardCapsEntries(t *testing.T) {
entries := make([]sandbox.RemoteDirEntry, 600)
for i := range entries {
entries[i] = sandbox.RemoteDirEntry{
Name: fmt.Sprintf("%03d.txt", i),
Path: fmt.Sprintf("/workspace/output/%03d.txt", i),
Type: sandbox.RemoteEntryFile,
}
}
source := &fakeSandboxFileSource{entries: entries}
result, err := NewListSandboxFilesTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"max_entries":999999}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, maxListSandboxMaxEntries, result.Data["count"])
assert.Equal(t, true, result.Data["truncated"])
assert.Equal(t, maxListSandboxMaxEntries, strings.Count(result.Output, "\n- "))
}

View File

@ -0,0 +1,507 @@
// Package tools — shell_exec.
//
// General shell command execution primitive for the agent. The LLM can freely
// explore and operate inside its session-scoped Cube MicroVM: inspect files,
// transform data, run programs, install dependencies, and prepare or verify
// skill outputs.
//
// Design notes:
//
// - Cube-only capability: registration is feature-gated on the sandbox
// backend exposing SandboxCommandExecutor. Docker / Local backends do
// NOT satisfy the interface, preserving their existing stateless
// security model. shell_exec never runs on the WeKnora host.
// - Session-scoped: the sandbox is resolved from ToolExecContext.SessionID
// so the LLM cannot execute against a foreign session, and installed
// dependencies persist across subsequent tool calls in the same session.
// - Non-zero exit is a normal signal, not an error: pip install failures,
// missing binaries, etc. are all valid results the LLM must inspect.
// Only wire-level errors (sandbox unreachable, timeout) surface as
// ToolResult.Success = false.
// - Output truncation: shell installers produce thousands of lines that
// would blow up the LLM context. We keep the head (leading messages)
// and the tail (final errors) with an ellipsis marker so the tail —
// usually the most informative segment — is preserved.
// - Command shape blacklist: the sandbox is throwaway, but we still refuse
// obviously destructive patterns (rm -rf /, fork bombs, mkfs...) to
// protect the LLM from its own hallucinations.
// - No backgrounding, no stdin: matches the confirmed product decisions.
// Trailing '&' and 'nohup' are rejected up-front to avoid orphaned
// processes inside the sandbox.
package tools
import (
"context"
"encoding/json"
"fmt"
"path"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// SandboxCommandExecutor is the narrow, tool-facing subset of a session-aware
// sandbox manager that supports executing arbitrary shell commands. In
// production it is satisfied by *sandbox.SessionBoundManager; tests can stub
// it with an in-memory fake. Kept local to the tools package for the same
// reason as SandboxFileSource — no dependency leak into higher layers.
type SandboxCommandExecutor interface {
ExecShellCommand(
ctx context.Context,
sessionID string,
command string,
workDir string,
timeout time.Duration,
env map[string]string,
) (*sandbox.ExecuteResult, error)
}
// Limits — kept generous enough for `pip install tensorflow` while still
// bounding the LLM context blast radius.
const (
// defaultShellExecWorkDir is where commands land when the caller omits
// work_dir. Matches CubeSandbox.Execute's remote directory convention.
defaultShellExecWorkDir = "/workspace"
// defaultShellExecTimeout is applied when the caller omits timeout_sec.
// 120s is enough for most pip installs; heavier installs can opt in via
// timeout_sec up to shellExecMaxTimeout.
defaultShellExecTimeout = 120 * time.Second
// shellExecMaxTimeout hard-caps timeout_sec. Ten minutes covers even the
// slow "install libreoffice" case without letting a runaway command
// pin the session's sandbox for hours.
shellExecMaxTimeout = 10 * time.Minute
// shellExecMaxCommandBytes rejects excessively long command strings.
// Real skill setup scripts fit comfortably under 8 KiB.
shellExecMaxCommandBytes = 8 * 1024
// max_output_bytes controls stdout only. Stderr uses a smaller independent
// budget so verbose failures cannot consume the entire tool result.
defaultShellExecOutputBytes = 16 * 1024
maxShellExecOutputBytes = 64 * 1024
defaultShellExecStderrBytes = 8 * 1024
maxShellExecStderrBytes = 16 * 1024
maxShellExecErrorBytes = 4 * 1024
maxShellExecVisibleBytes = 64 * 1024
)
// Blacklist patterns. These are cheap sanity checks, not a security
// perimeter — the Cube MicroVM session isolation is the real perimeter.
// The intent is to prevent the LLM from bricking its own session with a
// hallucinated one-liner (e.g. `rm -rf /`).
//
// Each entry is a compiled regexp; we return the first matching entry's
// name in the error so the LLM sees exactly why its command was rejected
// and can adjust.
var shellExecBlacklist = []struct {
name string
re *regexp.Regexp
}{
// `rm -rf /` and variants (including `rm -Rf --no-preserve-root /`).
// Reject any rm with a recursive+force flag targeting the filesystem
// root. We intentionally do NOT block `rm -rf /workspace/foo` — a
// skill legitimately might clean up its scratch directory.
{name: "rm_root", re: regexp.MustCompile(`(?i)\brm\s+(?:-[a-z]*[rR][a-z]*[fF][a-z]*|-[a-z]*[fF][a-z]*[rR][a-z]*|--recursive[^;|&]*--force|--force[^;|&]*--recursive)\s+(?:--no-preserve-root\s+)?/(?:\s|$)`)},
// Classic fork bomb.
{name: "fork_bomb", re: regexp.MustCompile(`:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:`)},
// Filesystem-format / raw-device writes.
{name: "mkfs", re: regexp.MustCompile(`(?i)\bmkfs(\.[a-z0-9]+)?\b`)},
{name: "dd_to_device", re: regexp.MustCompile(`(?i)\bdd\b[^;|&]*\bof=/dev/`)},
// Host-level power management. Even inside a MicroVM these serve no
// legitimate skill purpose and would just tear down the session.
{name: "shutdown", re: regexp.MustCompile(`(?i)\b(shutdown|reboot|halt|poweroff)\b`)},
// Explicit backgrounding is a product decision (see file header). Trailing
// `&` (but not `&&`) or a `nohup` prefix indicates the LLM tried to
// detach a process.
{name: "background_amp", re: regexp.MustCompile(`(?:^|[^&])&\s*(?:#.*)?$`)},
{name: "nohup", re: regexp.MustCompile(`(?i)(^|[;|&\s])nohup\b`)},
}
// Tool schema
var shellExecTool = BaseTool{
name: ToolShellExec,
description: `Run a shell command inside the current session's isolated remote sandbox.
## Usage
- Use freely to explore and operate inside the sandbox: inspect files, search
content, transform data, run programs, manage dependencies, install system packages and verify outputs.
- If a 'command not found' error occurs, attempt to resolve it by running ` + "`apt-get update && apt-get install -y <package>`" + `, or use any other appropriate method to install the missing command.
- User-uploaded files listed in ` + "`<sandbox_attachments>`" + ` are restored under
` + "`/workspace/input`" + `. Treat them as read-only inputs; write generated files
under ` + "`/workspace/output`" + `.
- Prefer standard Unix tools for filesystem work: ` + "`find`" + ` / ` + "`file`" + ` to discover
files and types; ` + "`cat`" + ` / ` + "`head`" + ` / ` + "`tail`" + ` / ` + "`sed`" + ` to inspect
text; ` + "`grep`" + ` / ` + "`awk`" + ` to search and process it.
- Install skill dependencies (` + "`pip install ...`" + `, ` + "`apt-get update && apt-get install -y ...`" + `,
` + "`npm i ...`" + `) before calling ` + "`execute_skill_script`" + ` when required.
## When to Use
- Whenever executing a command is the most direct way to complete the task.
- To inspect any text file or directory in the sandbox, including system paths.
- To chain shell pipelines, unpack archives, compile or run code, and prepare
intermediate files for later commands or skills.
## When NOT to Use
- DO NOT use this to run a skill's main script — use ` + "`execute_skill_script`" + `
which handles skill lookup, artifact collection, and proper interpreter
selection.
- DO NOT try to background processes (` + "`&`" + ` at the end, ` + "`nohup`" + `). Sandbox
execution is synchronous.
## Parameters
- ` + "`command`" + ` (required): the shell one-liner to run under ` + "`/bin/bash -l -c`" + `.
Supports pipes, redirects, ` + "`&&`" + ` / ` + "`||`" + ` chaining.
- ` + "`work_dir`" + ` (optional): working directory, defaults to ` + "`/workspace`" + `.
Created on demand if it doesn't exist.
- ` + "`timeout_sec`" + ` (optional): per-call timeout in seconds. Defaults to 120,
capped at 600. Large installs (LibreOffice, TensorFlow) may need the cap.
- ` + "`max_output_bytes`" + ` (optional): maximum bytes returned from stdout.
Defaults to 16384, capped at 65536. Stderr is independently limited to 8192
bytes by default; ` + "`max_stderr_bytes`" + ` may raise it to at most 16384.
The complete visible result is always capped at 65536 bytes.
- ` + "`env`" + ` (optional): extra environment variables merged on top of the
sandbox's base env, e.g. ` + "`{\"PIP_INDEX_URL\": \"https://mirrors.tencent.com/pypi/simple\"}`" + `.
## Returns
- ` + "`exit_code`" + `: 0 on success, non-zero on failure. Non-zero is NOT a tool
error — the tool call succeeds; you should read stderr and decide what to
do next (retry, adjust arguments, tell the user).
- ` + "`stdout`" + ` / ` + "`stderr`" + `: captured output, truncated to preserve context
budget. The tail is preserved when truncation happens, since the final
lines usually carry the crucial error message.
- Binary output is never returned to the model. Store binary files under
` + "`/workspace/output`" + ` so ArtifactCollector can expose them for download.
- ` + "`duration_ms`" + `: wall-clock execution time.
## Safety
- The command runs inside a session-scoped MicroVM: destructive commands
only affect this session's sandbox, never the host or other sessions.
- Obviously destructive patterns (` + "`rm -rf /`" + `, fork bombs, ` + "`mkfs`" + `, ` + "`shutdown`" + `)
are refused up-front. Cleaning up your own scratch dir (e.g.
` + "`rm -rf /workspace/tmp`" + `) is fine.
- Only available when the sandbox backend is Remote SandBox. On Docker / Local
deployments this tool is not registered.`,
schema: utils.GenerateSchema[ShellExecInput](),
}
// ShellExecInput defines the input parameters for shell_exec.
type ShellExecInput struct {
// Command is the shell command to execute. Runs under `/bin/bash -l -c`.
Command string `json:"command" jsonschema:"Shell command to execute (single line, supports pipes and && chaining). Runs under /bin/bash -l -c."`
// WorkDir is the working directory for the command; defaults to /workspace.
WorkDir string `json:"work_dir,omitempty" jsonschema:"Working directory for the command. Defaults to /workspace. Created on demand if missing."`
// TimeoutSec caps execution time. Zero uses the default (120s); the
// value is hard-capped at 600s regardless of what the LLM requests.
TimeoutSec int `json:"timeout_sec,omitempty" jsonschema:"Per-call timeout in seconds. Defaults to 120, hard-capped at 600."`
// MaxOutputBytes caps returned stdout. Stderr has an independent smaller
// fixed budget, and the complete model-visible output is capped at 64 KiB.
MaxOutputBytes int `json:"max_output_bytes,omitempty" jsonschema:"Maximum bytes returned from stdout. Defaults to 16384, hard-capped at 65536. Stderr defaults to 8192 and is hard-capped at 16384; total visible output is hard-capped at 65536."`
// MaxStderrBytes caps returned stderr independently from stdout.
MaxStderrBytes int `json:"max_stderr_bytes,omitempty" jsonschema:"Maximum bytes returned from stderr. Defaults to 8192, hard-capped at 16384."`
// Env carries extra environment variables merged into the shell's env.
Env map[string]string `json:"env,omitempty" jsonschema:"Optional extra environment variables, e.g. {\"PIP_INDEX_URL\":\"https://mirrors.example.com/pypi/simple\"}."`
}
// ShellExecTool executes shell commands inside the session's sandbox.
type ShellExecTool struct {
BaseTool
executor SandboxCommandExecutor
}
// NewShellExecTool constructs the tool. `executor` MUST NOT be nil:
// callers should feature-gate registration when the sandbox backend
// does not support ad-hoc shell execution (i.e. is not Cube).
func NewShellExecTool(executor SandboxCommandExecutor) *ShellExecTool {
return &ShellExecTool{
BaseTool: shellExecTool,
executor: executor,
}
}
// OutputLimitChars lets ToolRegistry preserve shell_exec's explicitly bounded,
// caller-configurable output instead of applying its lower generic limit again.
func (t *ShellExecTool) OutputLimitChars(args json.RawMessage) int {
return maxShellExecVisibleBytes
}
// Execute runs the requested command inside the current session's sandbox.
func (t *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][ShellExec] Execute started")
var input ShellExecInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("Failed to parse args: %v", err),
}, nil
}
if t.executor == nil {
return &types.ToolResult{
Success: false,
Error: "shell_exec is not available in this deployment (remote sandbox required)",
}, nil
}
command := strings.TrimSpace(input.Command)
if command == "" {
return &types.ToolResult{
Success: false,
Error: "command is required",
}, nil
}
if len(command) > shellExecMaxCommandBytes {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("command too long (%d bytes; max %d)", len(command), shellExecMaxCommandBytes),
}, nil
}
if reason := checkShellExecBlacklist(command); reason != "" {
logger.Warnf(ctx, "[Tool][ShellExec] rejected by blacklist: %s command=%q", reason, command)
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("command rejected by shell_exec safety guard: %s", reason),
}, nil
}
sessionID := resolveSessionID(ctx)
if sessionID == "" {
return &types.ToolResult{
Success: false,
Error: "no session ID in context; shell_exec must run inside an agent turn",
}, nil
}
workDir := strings.TrimSpace(input.WorkDir)
if workDir == "" {
workDir = defaultShellExecWorkDir
}
cleanWorkDir := path.Clean(workDir)
if !isUnderRoot(cleanWorkDir, defaultShellExecWorkDir) {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"work_dir %q is outside the sandbox workspace %q",
input.WorkDir, defaultShellExecWorkDir,
),
}, nil
}
workDir = cleanWorkDir
timeout := defaultShellExecTimeout
if input.TimeoutSec > 0 {
timeout = time.Duration(input.TimeoutSec) * time.Second
}
if timeout > shellExecMaxTimeout {
timeout = shellExecMaxTimeout
}
logger.Infof(ctx, "[Tool][ShellExec] session=%s work_dir=%s timeout=%s command=%q",
sessionID, workDir, timeout, command)
res, err := t.executor.ExecShellCommand(ctx, sessionID, command, workDir, timeout, input.Env)
if err != nil {
logger.Warnf(ctx, "[Tool][ShellExec] execution error: session=%s err=%v", sessionID, err)
errorText, _ := truncateShellStream(fmt.Sprintf("shell_exec failed: %v", err), maxShellExecErrorBytes)
return &types.ToolResult{
Success: false,
Error: errorText,
}, nil
}
outputLimit := resolveShellOutputLimit(input.MaxOutputBytes)
stderrLimit := resolveShellStderrLimit(input.MaxStderrBytes)
stdout, stdoutTruncated, stdoutBinary := prepareShellStream(res.Stdout, outputLimit)
stderr, stderrTruncated, stderrBinary := prepareShellStream(res.Stderr, stderrLimit)
errorText, errorTruncated := truncateShellStream(res.Error, maxShellExecErrorBytes)
truncated := stdoutTruncated || stderrTruncated || errorTruncated
// Human-readable summary for the LLM.
var b strings.Builder
b.WriteString(fmt.Sprintf("=== Shell Exec (session=%s) ===\n\n", sessionID))
b.WriteString(fmt.Sprintf("**Command**: `%s`\n", command))
b.WriteString(fmt.Sprintf("**Work Dir**: %s\n", workDir))
b.WriteString(fmt.Sprintf("**Exit Code**: %d\n", res.ExitCode))
b.WriteString(fmt.Sprintf("**Duration**: %v\n", res.Duration))
if res.Killed {
b.WriteString("**Killed**: yes (timeout or terminated)\n")
}
if truncated {
b.WriteString("**Truncated**: yes (head+tail kept; run `tail -n 200 <logfile>` inside the sandbox for full output)\n")
}
if stdoutBinary || stderrBinary {
b.WriteString("**Binary Output Suppressed**: yes (write binary files to the artifact output directory for download)\n")
}
b.WriteString("\n")
if stdout != "" {
b.WriteString("## Stdout\n\n```\n")
b.WriteString(stdout)
if !strings.HasSuffix(stdout, "\n") {
b.WriteString("\n")
}
b.WriteString("```\n\n")
}
if stderr != "" {
b.WriteString("## Stderr\n\n```\n")
b.WriteString(stderr)
if !strings.HasSuffix(stderr, "\n") {
b.WriteString("\n")
}
b.WriteString("```\n\n")
}
if errorText != "" {
b.WriteString("## Error\n\n")
b.WriteString(errorText)
b.WriteString("\n")
}
visibleOutput := b.String()
visibleOutput, totalTruncated := truncateShellStream(visibleOutput, maxShellExecVisibleBytes)
truncated = truncated || errorTruncated || totalTruncated
// The tool call itself succeeds even when the shell command exits non-zero:
// the LLM needs stderr/exit_code as first-class signals to iterate. We
// only mark Success=false when a wire-level problem prevented the command
// from running at all (already handled above via err != nil).
resultData := map[string]interface{}{
"session_id": sessionID,
"command": command,
"work_dir": workDir,
"exit_code": res.ExitCode,
"stdout": stdout,
"stderr": stderr,
"duration_ms": res.Duration.Milliseconds(),
"killed": res.Killed,
"truncated": truncated,
"stdout_truncated": stdoutTruncated,
"stderr_truncated": stderrTruncated,
"stdout_binary": stdoutBinary,
"stderr_binary": stderrBinary,
"stdout_bytes": len(res.Stdout),
"stderr_bytes": len(res.Stderr),
"stdout_original_bytes": len(res.Stdout),
"stdout_returned_bytes": len(stdout),
"stderr_original_bytes": len(res.Stderr),
"stderr_returned_bytes": len(stderr),
"error_original_bytes": len(res.Error),
"error_returned_bytes": len(errorText),
"error_truncated": errorTruncated,
"total_truncated": totalTruncated,
"visible_original_bytes": b.Len(),
"visible_returned_bytes": len(visibleOutput),
"max_output_bytes": outputLimit,
"max_stderr_bytes": stderrLimit,
}
logger.Infof(ctx, "[Tool][ShellExec] session=%s exit=%d duration=%v killed=%v truncated=%v",
sessionID, res.ExitCode, res.Duration, res.Killed, truncated)
return &types.ToolResult{
Success: true,
Output: visibleOutput,
Data: resultData,
}, nil
}
func resolveShellOutputLimit(requested int) int {
if requested <= 0 {
return defaultShellExecOutputBytes
}
if requested > maxShellExecOutputBytes {
return maxShellExecOutputBytes
}
return requested
}
func resolveShellStderrLimit(requested int) int {
if requested <= 0 {
return defaultShellExecStderrBytes
}
if requested > maxShellExecStderrBytes {
return maxShellExecStderrBytes
}
return requested
}
// prepareShellStream suppresses binary data before it can enter ToolResult
// Output or Data. Text streams are bounded using head+tail preservation.
func prepareShellStream(s string, limit int) (output string, truncated, binary bool) {
if isBinaryShellOutput(s) {
return "", false, true
}
output, truncated = truncateShellStream(s, limit)
return output, truncated, false
}
func isBinaryShellOutput(s string) bool {
if s == "" {
return false
}
if !utf8.ValidString(s) || strings.IndexByte(s, 0) >= 0 {
return true
}
// Any non-text control byte is enough to suppress the stream. ANSI terminal
// escapes remain allowed so ordinary colored command output stays readable.
for _, r := range s {
if r < 0x20 && r != '\n' && r != '\r' && r != '\t' &&
r != '\b' && r != '\f' && r != 0x1b {
return true
}
}
return false
}
// Cleanup releases any resources.
func (t *ShellExecTool) Cleanup(ctx context.Context) error {
return nil
}
// checkShellExecBlacklist reports a non-empty reason string when command
// matches one of the blacklist patterns. Returns "" for allowed commands.
func checkShellExecBlacklist(command string) string {
for _, entry := range shellExecBlacklist {
if entry.re.MatchString(command) {
return entry.name
}
}
return ""
}
// truncateShellStream reduces s to at most limit bytes by keeping the head
// and tail of the stream. The tail is prioritised because the final lines
// of a shell run almost always carry the actionable diagnostic (success
// marker, traceback, "ERROR: could not find matching distribution").
//
// Returns the (possibly truncated) content and a flag indicating whether
// any trimming happened.
func truncateShellStream(s string, limit int) (string, bool) {
if limit <= 0 || len(s) <= limit {
return s, false
}
// Include the marker inside the byte budget. Its omitted-byte count depends
// on the retained size, so compute it once, then recalculate the final split.
marker := fmt.Sprintf("\n...[truncated %d bytes]...\n", len(s)-limit)
if len(marker) >= limit {
return s[len(s)-limit:], true
}
kept := limit - len(marker)
head := kept / 4
tail := kept - head
marker = fmt.Sprintf("\n...[truncated %d bytes]...\n", len(s)-head-tail)
if len(marker) != limit-kept {
kept = limit - len(marker)
head = kept / 4
tail = kept - head
}
var b strings.Builder
b.Grow(limit)
b.WriteString(s[:head])
b.WriteString(marker)
b.WriteString(s[len(s)-tail:])
return b.String(), true
}

View File

@ -0,0 +1,174 @@
package tools
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type fakeShellExecutor struct {
result *sandbox.ExecuteResult
err error
timeout time.Duration
}
func (f *fakeShellExecutor) ExecShellCommand(
_ context.Context,
_ string,
_ string,
_ string,
timeout time.Duration,
_ map[string]string,
) (*sandbox.ExecuteResult, error) {
f.timeout = timeout
if f.err != nil {
return nil, f.err
}
if f.result == nil {
return &sandbox.ExecuteResult{ExitCode: 0}, nil
}
return f.result, nil
}
func shellExecTestContext() context.Context {
return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "session-1"})
}
func TestShellExecRejectsWorkDirOutsideWorkspace(t *testing.T) {
executor := &fakeShellExecutor{}
tool := NewShellExecTool(executor)
result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
`{"command":"pwd","work_dir":"/etc"}`,
))
require.NoError(t, err)
require.False(t, result.Success)
require.Contains(t, result.Error, "outside the sandbox workspace")
assert.Equal(t, time.Duration(0), executor.timeout)
}
func TestShellExecTimeoutHonorsAndCapsRequestedValue(t *testing.T) {
executor := &fakeShellExecutor{}
tool := NewShellExecTool(executor)
result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
`{"command":"sleep 1","timeout_sec":999}`,
))
require.NoError(t, err)
require.True(t, result.Success)
assert.Equal(t, shellExecMaxTimeout, executor.timeout)
}
func TestShellExecConfigurableOutputAndRegistryOverride(t *testing.T) {
content := strings.Repeat("x", 24*1024)
executor := &fakeShellExecutor{result: &sandbox.ExecuteResult{
Stdout: content,
ExitCode: 0,
}}
registry := NewToolRegistry()
registry.RegisterTool(NewShellExecTool(executor))
result, err := registry.ExecuteTool(shellExecTestContext(), ToolShellExec, json.RawMessage(
`{"command":"cat large.txt","max_output_bytes":32768}`,
))
require.NoError(t, err)
require.True(t, result.Success)
assert.Contains(t, result.Output, content)
assert.NotContains(t, result.Output, "output truncated")
assert.Equal(t, 32768, result.Data["max_output_bytes"])
}
func TestShellExecOutputLimitIsHardCapped(t *testing.T) {
tool := NewShellExecTool(&fakeShellExecutor{})
limit := tool.OutputLimitChars(json.RawMessage(`{"max_output_bytes":999999}`))
assert.Equal(t, maxShellExecVisibleBytes, limit)
}
func TestShellExecSuppressesBinaryStreams(t *testing.T) {
binary := "prefix\x00\x01payload"
executor := &fakeShellExecutor{result: &sandbox.ExecuteResult{
Stdout: binary,
Stderr: "text error",
ExitCode: 0,
}}
tool := NewShellExecTool(executor)
result, err := tool.Execute(shellExecTestContext(), json.RawMessage(`{"command":"cat image.bin"}`))
require.NoError(t, err)
require.True(t, result.Success)
assert.NotContains(t, result.Output, binary)
assert.Contains(t, result.Output, "Binary Output Suppressed")
assert.Equal(t, "", result.Data["stdout"])
assert.Equal(t, true, result.Data["stdout_binary"])
assert.Equal(t, len(binary), result.Data["stdout_bytes"])
assert.Equal(t, "text error", result.Data["stderr"])
}
func TestShellExecDescriptionSupportsGeneralExploration(t *testing.T) {
description := NewShellExecTool(&fakeShellExecutor{}).Description()
for _, command := range []string{"find", "file", "sed", "head", "tail", "cat", "grep", "awk"} {
assert.Contains(t, description, command)
}
assert.Contains(t, description, "Use freely to explore")
assert.Contains(t, description, "Binary output is never returned")
}
func TestShellExecBoundsStdoutStderrErrorAndTotal(t *testing.T) {
executor := &fakeShellExecutor{result: &sandbox.ExecuteResult{
Stdout: strings.Repeat("o", 100*1024),
Stderr: strings.Repeat("s", 40*1024) + "TAIL_ERROR",
Error: strings.Repeat("e", 8*1024),
}}
result, err := NewShellExecTool(executor).Execute(
shellExecTestContext(),
json.RawMessage(`{"command":"noisy","max_output_bytes":999999,"max_stderr_bytes":999999}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.LessOrEqual(t, len(result.Output), maxShellExecVisibleBytes)
assert.LessOrEqual(t, result.Data["stdout_returned_bytes"].(int), maxShellExecOutputBytes)
assert.LessOrEqual(t, result.Data["stderr_returned_bytes"].(int), maxShellExecStderrBytes)
assert.LessOrEqual(t, result.Data["error_returned_bytes"].(int), maxShellExecErrorBytes)
assert.Equal(t, true, result.Data["stdout_truncated"])
assert.Equal(t, true, result.Data["stderr_truncated"])
assert.Equal(t, true, result.Data["error_truncated"])
assert.Contains(t, result.Data["stderr"], "TAIL_ERROR")
}
func TestShellExecBoundsExecutorErrors(t *testing.T) {
executor := &fakeShellExecutor{err: errors.New(strings.Repeat("network failure ", 1024))}
result, err := NewShellExecTool(executor).Execute(
shellExecTestContext(),
json.RawMessage(`{"command":"echo hi"}`),
)
require.NoError(t, err)
require.False(t, result.Success)
assert.LessOrEqual(t, len(result.Error), maxShellExecErrorBytes)
assert.Contains(t, result.Error, "truncated")
}
func TestTruncateShellStreamIncludesMarkerWithinLimit(t *testing.T) {
output, truncated := truncateShellStream(strings.Repeat("x", 10000), 100)
require.True(t, truncated)
assert.LessOrEqual(t, len(output), 100)
assert.Contains(t, output, "truncated")
}

View File

@ -22,6 +22,11 @@ var executeSkillScriptTool = BaseTool{
- Use this tool to run utility scripts bundled with a skill
- Scripts are executed in an isolated sandbox for security
- Only scripts from loaded skills can be executed
- User-uploaded files are listed in the current ` + "`<sandbox_attachments>`" + `
block. Pass their absolute ` + "`/workspace/input/...`" + ` paths through
` + "`args`" + ` when a script accepts an input file.
- Treat ` + "`/workspace/input`" + ` as read-only. Write generated files only to
` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + ` so they can be collected for download.
## When to Use
- When a skill's instructions reference a utility script (e.g., "Run scripts/analyze_form.py")
@ -43,7 +48,7 @@ var executeSkillScriptTool = BaseTool{
type ExecuteSkillScriptInput struct {
SkillName string `json:"skill_name" jsonschema:"Name of the skill containing the script"`
ScriptPath string `json:"script_path" jsonschema:"Relative path to the script within the skill directory (e.g. scripts/analyze.py)"`
Args []string `json:"args,omitempty" jsonschema:"Optional command-line arguments to pass to the script. Note: if using --file flag, you must provide an actual file path that exists in the skill directory. If you have data in memory (not a file), use the 'input' parameter instead."`
Args []string `json:"args,omitempty" jsonschema:"Optional command-line arguments. For file flags, pass an absolute path from the current <sandbox_attachments> block (/workspace/input/...). For in-memory data, use input instead."`
Input string `json:"input,omitempty" jsonschema:"Optional input data to pass to the script via stdin. Use this when you have data in memory (e.g. JSON string) that the script should process. This is equivalent to piping data: echo 'data' | python script.py"`
}

View File

@ -73,3 +73,37 @@ func (r *customAgentRepository) CountByModelID(
err := query.Count(&count).Error
return count, err
}
// CountBySandboxConfigID counts agents pointing at a sandbox config.
//
// Used only to warn the admin which agents reference a config; never use it to
// refuse operations. Agent references are permanent state, so blocking on them
// would make credential rotation impossible.
func (r *customAgentRepository) CountBySandboxConfigID(
ctx context.Context, tenantID uint64, configID string,
) (int64, error) {
var count int64
query := r.db.WithContext(ctx).
Model(&types.CustomAgent{}).
Where("tenant_id = ?", tenantID)
query = scopeCustomAgentsBySandboxConfigID(query, configID)
err := query.Count(&count).Error
return count, err
}
// ListNamesBySandboxConfigID returns agent names pointing at a sandbox config.
//
// Used only to warn the admin which agents reference a config; never use it to
// refuse operations. Agent references are permanent state, so blocking on them
// would make credential rotation impossible.
func (r *customAgentRepository) ListNamesBySandboxConfigID(
ctx context.Context, tenantID uint64, configID string,
) ([]string, error) {
var names []string
query := r.db.WithContext(ctx).
Model(&types.CustomAgent{}).
Where("tenant_id = ?", tenantID)
query = scopeCustomAgentsBySandboxConfigID(query, configID)
err := query.Order("name ASC").Pluck("name", &names).Error
return names, err
}

View File

@ -267,3 +267,67 @@ func (r *messageRepository) UpdateMessageKnowledgeID(
Where("id = ?", messageID).
Update("knowledge_id", knowledgeID).Error
}
// GetSessionArtifacts returns every skill-produced MessageArtifact recorded
// against any assistant message of the session, in creation order.
//
// Projection is scoped to the artifacts JSONB column plus created_at (used
// to order the flattened output). Assistant messages without artifacts (the
// common case) contribute an empty slice and cost nothing extra.
func (r *messageRepository) GetSessionArtifacts(
ctx context.Context, sessionID string,
) (types.MessageArtifacts, error) {
if sessionID == "" {
return nil, nil
}
var rows []struct {
Artifacts types.MessageArtifacts `gorm:"column:artifacts"`
CreatedAt time.Time `gorm:"column:created_at"`
}
if err := r.db.WithContext(ctx).
Model(&types.Message{}).
Select("artifacts", "created_at").
Where("session_id = ? AND deleted_at IS NULL", sessionID).
Order("created_at ASC").
Find(&rows).Error; err != nil {
return nil, err
}
if len(rows) == 0 {
return types.MessageArtifacts{}, nil
}
result := make(types.MessageArtifacts, 0, len(rows))
for _, row := range rows {
if len(row.Artifacts) == 0 {
continue
}
result = append(result, row.Artifacts...)
}
return result, nil
}
// GetSessionAttachments returns every user-uploaded attachment in creation
// order while projecting only the attachments JSON column.
func (r *messageRepository) GetSessionAttachments(
ctx context.Context, sessionID string,
) (types.MessageAttachments, error) {
if sessionID == "" {
return nil, nil
}
var rows []struct {
Attachments types.MessageAttachments `gorm:"column:attachments"`
CreatedAt time.Time `gorm:"column:created_at"`
}
if err := r.db.WithContext(ctx).
Model(&types.Message{}).
Select("attachments", "created_at").
Where("session_id = ? AND deleted_at IS NULL", sessionID).
Order("created_at ASC").
Find(&rows).Error; err != nil {
return nil, err
}
result := make(types.MessageAttachments, 0, len(rows))
for _, row := range rows {
result = append(result, row.Attachments...)
}
return result, nil
}

View File

@ -49,3 +49,10 @@ func scopeCustomAgentsByModelID(db *gorm.DB, modelID string) *gorm.DB {
modelID, modelID, modelID, modelID, modelID, modelID,
)
}
func scopeCustomAgentsBySandboxConfigID(db *gorm.DB, configID string) *gorm.DB {
if db.Dialector.Name() == "postgres" {
return db.Where("config->>'sandbox_config_id' = ?", configID)
}
return db.Where("json_extract(config, '$.sandbox_config_id') = ?", configID)
}

View File

@ -111,3 +111,28 @@ func TestCountByModelID_CustomAgent(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, int64(1), count)
}
func TestCustomAgentSandboxConfigReferences(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)
repo := NewCustomAgentRepository(db)
configID := "sandbox-cfg-1"
require.NoError(t, db.Exec(
`INSERT INTO custom_agents (id, name, tenant_id, config) VALUES
(?, ?, ?, ?),
(?, ?, ?, ?),
(?, ?, ?, ?)`,
uuid.New().String(), "analysis-agent", 1, `{"sandbox_config_id":"sandbox-cfg-1"}`,
uuid.New().String(), "other-agent", 1, `{"sandbox_config_id":"sandbox-cfg-2"}`,
uuid.New().String(), "other-tenant-agent", 2, `{"sandbox_config_id":"sandbox-cfg-1"}`,
).Error)
count, err := repo.CountBySandboxConfigID(ctx, 1, configID)
require.NoError(t, err)
assert.Equal(t, int64(1), count)
names, err := repo.ListNamesBySandboxConfigID(ctx, 1, configID)
require.NoError(t, err)
assert.Equal(t, []string{"analysis-agent"}, names)
}

View File

@ -0,0 +1,135 @@
// Package repository persists sandbox backend configuration.
//
// Every read and write is scoped by tenant_id. Sandbox configs carry provider
// credentials, so a query that forgets the scope is a cross-workspace credential
// leak, not merely a bug.
package repository
import (
"context"
"errors"
"time"
"github.com/Tencent/WeKnora/internal/types"
"gorm.io/gorm"
)
// TenantSandboxConfigRepository persists named sandbox backend configs.
type TenantSandboxConfigRepository interface {
Create(ctx context.Context, e *types.TenantSandboxConfigEntity) error
GetByID(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantSandboxConfigEntity, error)
Update(ctx context.Context, e *types.TenantSandboxConfigEntity) error
SoftDelete(ctx context.Context, tenantID uint64, id string) error
SetCordon(ctx context.Context, tenantID uint64, id string, at time.Time) error
ClearCordon(ctx context.Context, tenantID uint64, id string) error
}
type tenantSandboxConfigRepository struct {
db *gorm.DB
}
// NewTenantSandboxConfigRepository returns a GORM-backed implementation.
func NewTenantSandboxConfigRepository(db *gorm.DB) TenantSandboxConfigRepository {
return &tenantSandboxConfigRepository{db: db}
}
func (r *tenantSandboxConfigRepository) Create(
ctx context.Context, e *types.TenantSandboxConfigEntity,
) error {
return r.db.WithContext(ctx).Create(e).Error
}
// GetByID returns nil (no error) when the config does not exist or belongs to
// another workspace, so callers can render a 404 without inspecting errors.
func (r *tenantSandboxConfigRepository) GetByID(
ctx context.Context, tenantID uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
var e types.TenantSandboxConfigEntity
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).
First(&e).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &e, nil
}
func (r *tenantSandboxConfigRepository) ListByTenant(
ctx context.Context, tenantID uint64,
) ([]*types.TenantSandboxConfigEntity, error) {
var list []*types.TenantSandboxConfigEntity
err := r.db.WithContext(ctx).
Where("tenant_id = ?", tenantID).
Order("created_at ASC").
Find(&list).Error
if err != nil {
return nil, err
}
return list, nil
}
// Update writes the mutable columns. Select is explicit so a zero-valued
// CordonedAt on the passed entity cannot silently release someone else's lease.
func (r *tenantSandboxConfigRepository) Update(
ctx context.Context, e *types.TenantSandboxConfigEntity,
) error {
return r.db.WithContext(ctx).
Model(&types.TenantSandboxConfigEntity{}).
Where("tenant_id = ? AND id = ?", e.TenantID, e.ID).
Select("name", "description", "sandbox_type", "config", "updated_at").
Updates(map[string]any{
"name": e.Name,
"description": e.Description,
"sandbox_type": e.SandboxType,
"config": e.Config,
"updated_at": time.Now(),
}).Error
}
func (r *tenantSandboxConfigRepository) SoftDelete(
ctx context.Context, tenantID uint64, id string,
) error {
return r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).
Delete(&types.TenantSandboxConfigEntity{}).Error
}
// ErrSandboxConfigCordoned is returned by SetCordon when another request
// already holds a fresh cordon lease on the same config row.
var ErrSandboxConfigCordoned = errors.New("sandbox config is being modified by another request")
// SetCordon must be committed before the caller lists provider sandboxes:
// resolution paths only stop creating sandboxes once they can see it.
//
// The update is a conditional CAS: it refuses to overwrite a cordon that is
// still within the lease window, so two concurrent identity-change requests
// cannot race past each other.
func (r *tenantSandboxConfigRepository) SetCordon(
ctx context.Context, tenantID uint64, id string, at time.Time,
) error {
result := r.db.WithContext(ctx).
Model(&types.TenantSandboxConfigEntity{}).
Where("tenant_id = ? AND id = ?", tenantID, id).
Where("cordoned_at IS NULL OR cordoned_at < ?", at.Add(-types.SandboxCordonLease)).
Update("cordoned_at", at)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrSandboxConfigCordoned
}
return nil
}
func (r *tenantSandboxConfigRepository) ClearCordon(
ctx context.Context, tenantID uint64, id string,
) error {
return r.db.WithContext(ctx).
Model(&types.TenantSandboxConfigEntity{}).
Where("tenant_id = ? AND id = ?", tenantID, id).
Update("cordoned_at", nil).Error
}

View File

@ -0,0 +1,118 @@
package repository
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newSandboxConfigTestRepo(t *testing.T) (TenantSandboxConfigRepository, *gorm.DB) {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+uuid.NewString()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.TenantSandboxConfigEntity{}))
// AutoMigrate cannot express the partial unique index, so add it here to
// match the production migration.
require.NoError(t, db.Exec(
`CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_sandbox_configs_tenant_name
ON tenant_sandbox_configs (tenant_id, name) WHERE deleted_at IS NULL`).Error)
return NewTenantSandboxConfigRepository(db), db
}
func TestSandboxConfigRepoIsolatesTenants(t *testing.T) {
repo, _ := newSandboxConfigTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 1,
Name: "prod",
SandboxType: "e2b",
Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
}))
require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
ID: "cfg-b",
TenantID: 2,
Name: "prod",
SandboxType: "e2b",
Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
}))
// Same name in a different workspace is fine; cross-tenant reads are not.
got, err := repo.GetByID(ctx, 1, "cfg-b")
require.NoError(t, err)
require.Nil(t, got, "must not read another workspace's config")
list, err := repo.ListByTenant(ctx, 1)
require.NoError(t, err)
require.Len(t, list, 1)
require.Equal(t, "cfg-a", list[0].ID)
}
func TestSandboxConfigRepoRejectsDuplicateNameInTenant(t *testing.T) {
repo, _ := newSandboxConfigTestRepo(t)
ctx := context.Background()
base := func(id string) *types.TenantSandboxConfigEntity {
return &types.TenantSandboxConfigEntity{
ID: id,
TenantID: 1,
Name: "prod",
SandboxType: "e2b",
Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
}
}
require.NoError(t, repo.Create(ctx, base("cfg-1")))
require.Error(t, repo.Create(ctx, base("cfg-2")))
}
func TestSandboxConfigRepoSoftDeleteHidesRow(t *testing.T) {
repo, _ := newSandboxConfigTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 1,
Name: "prod",
SandboxType: "e2b",
Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
}))
require.NoError(t, repo.SoftDelete(ctx, 1, "cfg-a"))
got, err := repo.GetByID(ctx, 1, "cfg-a")
require.NoError(t, err)
require.Nil(t, got)
}
func TestSandboxConfigRepoCordonRoundTrip(t *testing.T) {
repo, _ := newSandboxConfigTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.Create(ctx, &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 1,
Name: "prod",
SandboxType: "e2b",
Config: &types.TenantSandboxConfig{SandboxType: "e2b"},
}))
at := time.Now().UTC().Truncate(time.Second)
require.NoError(t, repo.SetCordon(ctx, 1, "cfg-a", at))
got, err := repo.GetByID(ctx, 1, "cfg-a")
require.NoError(t, err)
require.NotNil(t, got.CordonedAt)
require.True(t, got.IsCordoned(at.Add(time.Second), types.SandboxCordonLease))
require.NoError(t, repo.ClearCordon(ctx, 1, "cfg-a"))
got, err = repo.GetByID(ctx, 1, "cfg-a")
require.NoError(t, err)
require.Nil(t, got.CordonedAt)
}

View File

@ -6,6 +6,7 @@ import (
"fmt"
"os"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/approval"
@ -103,6 +104,10 @@ type agentService struct {
tenantService interfaces.TenantService
storageResolver interfaces.StorageBackendResolver
toolApprovalGate approval.MCPApproval
sandboxMgr sandbox.Manager
sandboxResolver sandbox.TenantSandboxResolver
sandboxPinner *SessionSandboxPinner
sandboxPolicy WorkspaceSandboxPolicy
}
// NewAgentService creates a new agent service
@ -124,6 +129,10 @@ func NewAgentService(
tenantService interfaces.TenantService,
storageResolver interfaces.StorageBackendResolver,
toolApprovalGate approval.MCPApproval,
sandboxMgr sandbox.Manager,
sandboxResolver sandbox.TenantSandboxResolver,
sandboxPinner *SessionSandboxPinner,
sandboxPolicy WorkspaceSandboxPolicy,
) interfaces.AgentService {
return &agentService{
cfg: cfg,
@ -143,6 +152,10 @@ func NewAgentService(
tenantService: tenantService,
storageResolver: storageResolver,
toolApprovalGate: toolApprovalGate,
sandboxMgr: sandboxMgr,
sandboxResolver: sandboxResolver,
sandboxPinner: sandboxPinner,
sandboxPolicy: sandboxPolicy,
}
}
@ -217,7 +230,7 @@ func (s *agentService) CreateAgentEngine(
// Initialize skills manager if skills are enabled
if config.SkillsEnabled && len(config.SkillDirs) > 0 {
skillsManager, err := s.initializeSkillsManager(ctx, config, toolRegistry)
skillsManager, err := s.initializeSkillsManager(ctx, sessionID, config, toolRegistry)
if err != nil {
logger.Warnf(ctx, "Failed to initialize skills manager: %v", err)
} else if skillsManager != nil {
@ -336,52 +349,44 @@ func (s *agentService) resolveKBAndDocInfos(
return kbInfos, selectedDocs
}
// initializeSkillsManager creates and initializes the skills manager
// initializeSkillsManager creates and initializes the skills manager.
//
// The sandbox manager is resolved per workspace: backends differ in
// capability (E2B exposes a session file store, local does not), so tool
// registration below must inspect this workspace's real manager rather than a
// process-wide singleton. Workspaces without their own sandbox configuration
// resolve to the injected default.
func (s *agentService) initializeSkillsManager(
ctx context.Context,
sessionID string,
config *types.AgentConfig,
toolRegistry *tools.ToolRegistry,
) (*skills.Manager, error) {
// Initialize sandbox manager based on environment variables
// WEKNORA_SANDBOX_MODE: "docker", "local", "disabled" (default: "disabled")
// WEKNORA_SANDBOX_TIMEOUT: timeout in seconds (default: 60)
// WEKNORA_SANDBOX_DOCKER_IMAGE: custom Docker image (default: wechatopenai/weknora-sandbox:latest)
var sandboxMgr sandbox.Manager
var err error
tenantID, _ := types.TenantIDFromContext(ctx)
configID, err := sandboxConfigForExecution(ctx, s.sandboxPinner, sessionID, config.SandboxConfigID)
if err != nil {
return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)
}
sandboxMgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy)
if err != nil {
return nil, err
}
if sandboxMgr == nil {
sandboxMgr = sandbox.NewDisabledManager()
}
sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")
sandboxMode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
if sandboxMode == "" {
sandboxMode = "disabled"
}
dockerImage := os.Getenv("WEKNORA_SANDBOX_DOCKER_IMAGE")
if dockerImage == "" {
dockerImage = sandbox.DefaultDockerImage
}
sandboxTimeoutStr := os.Getenv("WEKNORA_SANDBOX_TIMEOUT")
sandboxTimeout := 60
if sandboxTimeoutStr != "" {
if v, err := strconv.Atoi(sandboxTimeoutStr); err == nil && v > 0 {
sandboxTimeout = v
if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
sandboxTimeout = n
}
}
switch sandboxMode {
case "docker":
sandboxMgr, err = sandbox.NewManagerFromType("docker", true, dockerImage) // Enable fallback to local
if err != nil {
logger.Warnf(ctx, "Failed to initialize Docker sandbox, falling back to disabled: %v", err)
sandboxMgr = sandbox.NewDisabledManager()
}
case "local":
sandboxMgr, err = sandbox.NewManagerFromType("local", false, "")
if err != nil {
logger.Warnf(ctx, "Failed to initialize local sandbox: %v", err)
sandboxMgr = sandbox.NewDisabledManager()
}
default:
sandboxMgr = sandbox.NewDisabledManager()
}
logger.Infof(ctx, "Sandbox configured: mode=%s, timeout=%ds, image=%s", sandboxMode, sandboxTimeout, dockerImage)
logger.Infof(ctx, "Sandbox in use: mode=%s type=%s timeout=%ds",
sandboxMode, sandboxMgr.GetType(), sandboxTimeout)
// Create skills manager
skillsConfig := &skills.ManagerConfig{
@ -402,10 +407,35 @@ func (s *agentService) initializeSkillsManager(
toolRegistry.RegisterTool(readSkillTool)
logger.Infof(ctx, "Registered read_skill tool")
if sandboxMode != "disabled" {
if sandboxMgr.GetType() != sandbox.SandboxTypeDisabled {
executeSkillTool := tools.NewExecuteSkillScriptTool(skillsManager)
toolRegistry.RegisterTool(executeSkillTool)
logger.Infof(ctx, "Registered execute_skill_script tool")
// list_sandbox_files / read_sandbox_file expose per-session
// filesystem inspection. Registration is gated on the sandbox
// manager advertising a SessionFileStore capability — providers
// that fell back to a stateless local sandbox return nil so we
// never surface tenant-isolated tools that would run on the
// WeKnora host.
if store := sessionSandboxFileStore(sandboxMgr); store != nil {
toolRegistry.RegisterTool(tools.NewListSandboxFilesTool(store))
toolRegistry.RegisterTool(tools.NewReadSandboxFileTool(store))
logger.Infof(ctx, "Registered list_sandbox_files and read_sandbox_file tools")
} else {
logger.Infof(ctx, "Sandbox backend does not advertise session filesystem capability; list_sandbox_files/read_sandbox_file not registered")
}
// shell_exec is a remote-only capability. SessionCapabilityProvider
// yields nil for stateless backends and for a SessionBoundManager
// that fell back to LocalSandbox, so the same check works for
// every provider (Cube, E2B, future backends).
if executor := sessionSandboxShellExecutor(sandboxMgr); executor != nil {
toolRegistry.RegisterTool(tools.NewShellExecTool(executor))
logger.Infof(ctx, "Registered shell_exec tool")
} else {
logger.Infof(ctx, "Sandbox backend does not advertise remote shell capability; shell_exec not registered")
}
}
return skillsManager, nil

View File

@ -0,0 +1,73 @@
package service
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/stretchr/testify/assert"
)
// capableManager is a test double that lets each case declare which
// session-scoped capabilities the sandbox manager currently advertises.
// It mirrors the real SessionCapabilityProvider contract SessionBoundManager
// implements, without pulling in the full manager wiring.
type capableManager struct {
typ sandbox.SandboxType
shell sandbox.SessionShellExecutor
files sandbox.SessionFileStore
}
func (m *capableManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
return &sandbox.ExecuteResult{}, nil
}
func (m *capableManager) Cleanup(context.Context) error { return nil }
func (m *capableManager) GetSandbox() sandbox.Sandbox { return nil }
func (m *capableManager) GetType() sandbox.SandboxType { return m.typ }
func (m *capableManager) SessionShellExecutor() sandbox.SessionShellExecutor {
return m.shell
}
func (m *capableManager) SessionFileStore() sandbox.SessionFileStore {
return m.files
}
// stubShellExecutor records ExecShellCommand calls so a test can assert the
// registered tool actually dispatches through it.
type stubShellExecutor struct{ called bool }
func (s *stubShellExecutor) ExecShellCommand(
context.Context, string, string, string, time.Duration, map[string]string,
) (*sandbox.ExecuteResult, error) {
s.called = true
return &sandbox.ExecuteResult{}, nil
}
func TestSessionSandboxShellExecutorReturnsNilWithoutCapability(t *testing.T) {
// Managers that don't implement SessionCapabilityProvider (Local /
// Docker / Disabled DefaultManager) must never surface shell_exec.
nonCapable := &capableManager{typ: sandbox.SandboxTypeLocal}
assert.Nil(t, sessionSandboxShellExecutor(nonCapable))
assert.Nil(t, sessionSandboxFileStore(nonCapable))
assert.Nil(t, sessionSandboxShellExecutor(nil))
}
func TestSessionSandboxShellExecutorReturnsNilWhenProviderRefuses(t *testing.T) {
// A provider that advertises capabilities but is currently unable to
// honour them (e.g. SessionBoundManager after Local fallback) returns
// nil from the accessor. The tool layer must respect that.
m := &capableManager{typ: sandbox.SandboxTypeCube}
assert.Nil(t, sessionSandboxShellExecutor(m))
assert.Nil(t, sessionSandboxFileStore(m))
}
func TestSessionSandboxShellExecutorReturnsCapability(t *testing.T) {
exec := &stubShellExecutor{}
m := &capableManager{typ: sandbox.SandboxTypeCube, shell: exec}
got := sessionSandboxShellExecutor(m)
assert.NotNil(t, got)
if _, err := got.ExecShellCommand(context.Background(), "sid", "echo", "", 0, nil); err != nil {
t.Fatalf("dispatch through capability: %v", err)
}
assert.True(t, exec.called)
}

View File

@ -0,0 +1,439 @@
// Package service - artifact collector.
//
// ArtifactCollector drains a session sandbox's output directory into the
// tenant file service after a skill turn finishes. It is intentionally kept
// stateless and testable: a narrow SandboxArtifactSource interface abstracts
// the sandbox side so unit tests can stub in a fake filesystem, and the
// file service is passed in so blobs land in the same storage backend the
// tenant already uses for uploaded attachments.
//
// Contract:
// - Never delete files from the sandbox — skills can share files across
// turns; deletion would break that (spec §2, "不清空输出目录").
// - Never lazy-create a sandbox: the collector reads from an already-live
// sandbox and returns an empty slice when none exists.
// - Best-effort: individual errors are logged and skipped, never returned,
// so a stray unreadable file cannot block the assistant reply.
// - De-duplication by (SourcePath, ModTime): if a prior message in the
// same session already recorded the same (path, mtime), skip it.
package service
import (
"context"
"path/filepath"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// SandboxArtifactSource is the narrow subset of sandbox behaviour the
// collector needs. SessionBoundManager satisfies it in production; tests
// use a fake to drive the diff logic without a real sandbox.
type SandboxArtifactSource interface {
ListSessionFiles(ctx context.Context, sessionID, dir string) ([]sandbox.RemoteDirEntry, error)
ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
}
// SessionArtifactStore is the minimal repository surface the collector needs
// to compute the "already recorded" set for a session. In production it is
// backed by the message repository; in tests it is stubbed with an in-memory
// map so the collector can be exercised without a database.
type SessionArtifactStore interface {
// KnownArtifacts returns every (SourcePath, ModTime) pair already
// attached to any prior message of the session. The returned set is
// unordered and safe to mutate by the caller.
KnownArtifacts(ctx context.Context, sessionID string) ([]types.MessageArtifact, error)
}
// ArtifactCollectorConfig bounds the collector's I/O and storage footprint.
// All fields have safe zero-value defaults applied by newBoundedConfig.
type ArtifactCollectorConfig struct {
// OutputDir is the absolute path inside the sandbox to scan. Empty
// falls back to skills.ArtifactOutputDir() at call time.
OutputDir string
// MaxFileBytes is the largest single file that will be persisted.
// Files larger than this are logged and skipped so a runaway skill
// cannot exhaust the WeKnora process's memory.
MaxFileBytes int64
}
// defaultMaxArtifactFileBytes caps a single artifact at 50 MiB. Larger files
// stream from the sandbox in a single ReadFile call today, so we cap here to
// protect the process from OOM. The cap can be raised via config once the
// sandbox client learns to stream to disk.
const defaultMaxArtifactFileBytes int64 = 50 * 1024 * 1024
// Resource binding coordinates for collected artifacts. The owner is the
// assistant message that produced the file (mirrors how knowledge uploads
// bind to "knowledge" and chat attachments bind to "temporary_document"),
// so the resource registry can enumerate / garbage-collect artifacts by
// their owning message instead of only via the messages.artifacts JSONB.
const (
artifactBindingOwnerType = "message"
artifactBindingRelation = "artifact"
)
// ArtifactCollector implements the "drain sandbox artifacts on turn
// completion" step described in
// docs/superpowers/specs/2026-07-10-skill-artifact-download-design.md §4.
type ArtifactCollector struct {
source SandboxArtifactSource
fileService interfaces.FileService
store SessionArtifactStore
// catalog binds each persisted artifact resource to its owning message.
// Optional: nil when the deployment runs without a resource registry, in
// which case artifacts are still saved and downloadable — they just are
// not tracked as owned resources.
catalog interfaces.ResourceCatalog
config ArtifactCollectorConfig
// resolver lets Collect use the workspace's own sandbox backend. Optional:
// nil keeps the process-wide source for every workspace.
resolver sandbox.TenantSandboxResolver
pinner *SessionSandboxPinner
// fallbackMgr is the deployment-wide SessionBoundManager. Sentinel pins
// ("-") resolve to it rather than a per-config manager.
fallbackMgr sandbox.Manager
}
// NewArtifactCollector wires up an ArtifactCollector. Callers keep a single
// instance per process; the collector holds no per-turn state. catalog may be
// nil (resource registry disabled); binding is then skipped.
func NewArtifactCollector(
source SandboxArtifactSource,
fileService interfaces.FileService,
store SessionArtifactStore,
catalog interfaces.ResourceCatalog,
config ArtifactCollectorConfig,
) *ArtifactCollector {
return &ArtifactCollector{
source: source,
fileService: fileService,
store: store,
catalog: catalog,
config: newBoundedConfig(config),
}
}
// NewArtifactCollectorFromSandboxManager is the DI-friendly constructor
// that promotes a sandbox.Manager to SandboxArtifactSource only when the
// underlying implementation actually supports per-session file inspection
// (currently *sandbox.SessionBoundManager). For any other backend the
// returned *ArtifactCollector is nil, which the AgentStreamHandler treats
// as "no artifacts to attach" — matching the graceful-degradation contract
// documented in the design spec.
// The resolver is consulted per turn so a workspace whose own backend supports
// artifacts still gets them even when the process-wide default does not. The
// collector is therefore built whenever either side could supply a source, and
// Collect degrades to "nothing to attach" when neither does.
func NewArtifactCollectorFromSandboxManager(
sandboxMgr sandbox.Manager,
sandboxResolver sandbox.TenantSandboxResolver,
pinner *SessionSandboxPinner,
fileService interfaces.FileService,
repo interfaces.MessageRepository,
catalog interfaces.ResourceCatalog,
) *ArtifactCollector {
if fileService == nil {
return nil
}
source, _ := sandboxMgr.(SandboxArtifactSource)
if source == nil && sandboxResolver == nil {
return nil
}
collector := NewArtifactCollector(
source,
fileService,
NewMessageRepoArtifactStore(repo),
catalog,
ArtifactCollectorConfig{},
)
collector.resolver = sandboxResolver
collector.pinner = pinner
collector.fallbackMgr = sandboxMgr
return collector
}
// sessionSource returns the artifact source for the sandbox pinned to
// sessionID, never the one the agent points at today: the sandbox being drained
// was created earlier and may live on a config the agent no longer selects.
//
// Returns nil when the session has no pin, which Collect treats as "nothing to
// attach".
func (c *ArtifactCollector) sessionSource(ctx context.Context, sessionID string) SandboxArtifactSource {
if c.resolver == nil {
return c.source
}
tenantID, _ := types.TenantIDFromContext(ctx)
configID, err := sandboxConfigForExistingSandbox(ctx, c.pinner, sessionID)
if err != nil {
logger.Warnf(ctx, "[ArtifactCollector] read sandbox pin failed: %v", err)
return nil
}
if configID == "" {
return nil
}
mgr, err := resolveTenantSandboxForConfig(
ctx, c.resolver, c.fallbackMgr, tenantID, configID, nil,
)
if err != nil {
// Refusing to read is the safe failure: substituting another backend
// would look in the wrong provider account and report "no artifacts".
logger.Warnf(ctx, "[ArtifactCollector] resolve sandbox failed: %v", err)
return nil
}
if mgr == nil {
// The pin names the deployment-wide default, which has no per-config
// manager of its own; the injected process-wide source IS that backend.
return c.source
}
if source, ok := mgr.(SandboxArtifactSource); ok {
return source
}
if configID == types.SandboxConfigIDGlobalDefault {
return c.source
}
return nil
}
// newBoundedConfig fills in defaults so callers can pass a zero
// ArtifactCollectorConfig without hitting empty-value edge cases.
func newBoundedConfig(cfg ArtifactCollectorConfig) ArtifactCollectorConfig {
if cfg.MaxFileBytes <= 0 {
cfg.MaxFileBytes = defaultMaxArtifactFileBytes
}
return cfg
}
// Collect scans the session sandbox's output directory and persists any
// newly-created or newly-modified files to the tenant file service.
//
// The returned slice contains one MessageArtifact per persisted file. When
// no sandbox is bound to the session, or when the source is nil (skill
// backend disabled), Collect returns nil, nil — the caller is expected to
// treat both cases as "nothing to attach" and NOT set message.Artifacts.
//
// Errors returned by Collect are limited to internal invariants (nil
// dependencies). Per-file errors (unreadable, too-large, upload failure)
// are logged and skipped so a single misbehaving artifact never breaks the
// turn.
func (c *ArtifactCollector) Collect(
ctx context.Context,
sessionID string,
messageID string,
tenantID uint64,
outputDir string,
) (types.MessageArtifacts, error) {
if c == nil || c.fileService == nil {
logger.Infof(ctx, "[ArtifactCollector] skipped: collector or dependencies nil (session=%s)", sessionID)
return nil, nil
}
source := c.sessionSource(ctx, sessionID)
if source == nil {
logger.Infof(ctx,
"[ArtifactCollector] skipped: sandbox backend has no session filesystem (session=%s)",
sessionID)
return nil, nil
}
if sessionID == "" {
logger.Infof(ctx, "[ArtifactCollector] skipped: empty sessionID")
return nil, nil
}
if outputDir == "" {
outputDir = c.config.OutputDir
}
if outputDir == "" {
// Callers should have resolved this via skills.ArtifactOutputDir
// but we guard here anyway to keep Collect self-contained.
logger.Infof(ctx, "[ArtifactCollector] skipped: empty outputDir (session=%s)", sessionID)
return nil, nil
}
logger.Infof(ctx, "[ArtifactCollector] begin session=%s dir=%s", sessionID, outputDir)
entries, err := source.ListSessionFiles(ctx, sessionID, outputDir)
if err != nil {
logger.Warnf(ctx, "[ArtifactCollector] list sandbox files failed: session=%s dir=%s err=%v",
sessionID, outputDir, err)
return nil, nil
}
if len(entries) == 0 {
// The most common cause of "download button never appears" is
// exactly this branch: either the sandbox was already reaped or
// the skill wrote to a different directory. Logging the exact
// (session, dir) pair makes it a 30-second grep to confirm.
logger.Infof(ctx, "[ArtifactCollector] no entries under %s (session=%s) — sandbox reaped or skill wrote elsewhere",
outputDir, sessionID)
return nil, nil
}
logger.Infof(ctx, "[ArtifactCollector] listed %d entries under %s (session=%s)", len(entries), outputDir, sessionID)
// Build a "already recorded" set so we don't double-attach the same
// file when several turns share the sandbox. Errors here degrade to an
// empty set: attaching duplicates is a soft failure, aborting is not.
known := c.loadKnownSet(ctx, sessionID)
if len(known) > 0 {
logger.Infof(ctx, "[ArtifactCollector] known set size=%d (session=%s)", len(known), sessionID)
}
artifacts := make(types.MessageArtifacts, 0, len(entries))
for _, entry := range entries {
art, ok := c.maybePersist(ctx, source, sessionID, messageID, tenantID, entry, known)
if !ok {
continue
}
artifacts = append(artifacts, art)
// Adding to the known set inside the loop protects us against the
// pathological case where ListSessionFiles returns the same path
// twice (envd hasn't been observed to do so, but future-proofing
// the loop is cheap).
known[artifactKey(art.SourcePath, art.ModTime)] = struct{}{}
}
logger.Infof(ctx, "[ArtifactCollector] done session=%s listed=%d attached=%d",
sessionID, len(entries), len(artifacts))
return artifacts, nil
}
// loadKnownSet returns the (source_path, mod_time) tuples already recorded
// against the session. Empty on error so the caller can proceed.
func (c *ArtifactCollector) loadKnownSet(ctx context.Context, sessionID string) map[string]struct{} {
set := map[string]struct{}{}
if c.store == nil {
return set
}
prev, err := c.store.KnownArtifacts(ctx, sessionID)
if err != nil {
logger.Warnf(ctx, "[ArtifactCollector] load previous artifacts failed: session=%s err=%v",
sessionID, err)
return set
}
for _, p := range prev {
set[artifactKey(p.SourcePath, p.ModTime)] = struct{}{}
}
return set
}
// maybePersist runs the per-file pipeline (filter → download → upload →
// build metadata). Returns ok=false when the entry was skipped for any
// reason (already known, too large, upload failed). All skip reasons are
// logged so operators can diagnose empty artifact panels.
func (c *ArtifactCollector) maybePersist(
ctx context.Context,
source SandboxArtifactSource,
sessionID string,
messageID string,
tenantID uint64,
entry sandbox.RemoteDirEntry,
known map[string]struct{},
) (types.MessageArtifact, bool) {
// Only files reach here (SessionBoundManager.listFilesRecursive filters
// directories), but we defensively double-check so callers passing an
// alternate SandboxArtifactSource don't break the assumption.
if entry.Type != sandbox.RemoteEntryFile {
return types.MessageArtifact{}, false
}
if entry.Path == "" || entry.Name == "" {
return types.MessageArtifact{}, false
}
if entry.Size > c.config.MaxFileBytes {
logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact: session=%s path=%s size=%d limit=%d",
sessionID, entry.Path, entry.Size, c.config.MaxFileBytes)
return types.MessageArtifact{}, false
}
modTime := entry.ModTime
key := artifactKey(entry.Path, modTime)
if _, seen := known[key]; seen {
return types.MessageArtifact{}, false
}
data, err := source.ReadSessionFile(ctx, sessionID, entry.Path)
if err != nil {
logger.Warnf(ctx, "[ArtifactCollector] read artifact failed: session=%s path=%s err=%v",
sessionID, entry.Path, err)
return types.MessageArtifact{}, false
}
// A second guard: envd may report a stale size while the file is being
// re-written; enforce the cap against the actual byte count too.
if int64(len(data)) > c.config.MaxFileBytes {
logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact after read: session=%s path=%s size=%d limit=%d",
sessionID, entry.Path, len(data), c.config.MaxFileBytes)
return types.MessageArtifact{}, false
}
// Give each blob a UUID-namespaced storage name so concurrent turns
// cannot collide, and so the storage key itself is unguessable from
// the outside (defence-in-depth on top of the /artifacts/:index
// endpoint's ownership check).
storageName := "artifact_" + uuid.NewString() + "_" + safeFileName(entry.Name)
storagePath, err := c.fileService.SaveBytes(ctx, data, tenantID, storageName, false)
if err != nil {
logger.Warnf(ctx, "[ArtifactCollector] upload artifact failed: session=%s path=%s err=%v",
sessionID, entry.Path, err)
return types.MessageArtifact{}, false
}
c.bindArtifactResource(ctx, storagePath, messageID)
return types.MessageArtifact{
URL: storagePath,
FileName: entry.Name,
FileType: strings.ToLower(filepath.Ext(entry.Name)),
FileSize: int64(len(data)),
SourcePath: entry.Path,
ModTime: modTime,
CreatedAt: time.Now().UTC(),
}, true
}
// bindArtifactResource records that the freshly-persisted artifact resource
// is owned by its assistant message. Best-effort: a binding failure never
// discards the artifact, because the file is already stored and remains
// downloadable through the /artifacts endpoint regardless of the binding.
//
// The binding is only attempted when (a) the catalog is wired in, (b) we have
// a message ID to own the resource, and (c) SaveBytes actually returned a
// resource:// reference — i.e. the file service is resource-catalog-backed.
// Raw provider paths (no catalog decorator) are left unbound rather than
// generating spurious "invalid resource reference" errors.
func (c *ArtifactCollector) bindArtifactResource(ctx context.Context, ref, messageID string) {
if c.catalog == nil || messageID == "" {
return
}
if _, ok := types.ParseResourcePath(ref); !ok {
return
}
if err := c.catalog.Bind(ctx, ref, artifactBindingOwnerType, messageID, artifactBindingRelation); err != nil {
logger.Warnf(ctx, "[ArtifactCollector] bind artifact resource failed: message=%s ref=%s err=%v",
messageID, ref, err)
}
}
// artifactKey is the string form of the (source_path, mtime) tuple used to
// de-duplicate artifacts across messages. mtime is normalised to UTC + RFC3339
// nano so equality is stable across time-zone or precision differences
// between sandbox envd builds.
func artifactKey(path string, mod time.Time) string {
if mod.IsZero() {
return path + "\x00"
}
return path + "\x00" + mod.UTC().Format(time.RFC3339Nano)
}
// safeFileName strips slashes and backslashes from the original name before
// concatenating it into the storage key. The FileService may or may not
// sanitise on its own; belt-and-suspenders here avoids provider-specific
// surprises (e.g. object stores that treat "/" as delimiter).
func safeFileName(name string) string {
name = strings.ReplaceAll(name, "/", "_")
name = strings.ReplaceAll(name, "\\", "_")
if name == "" {
return "unnamed"
}
return name
}

View File

@ -0,0 +1,36 @@
package service
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// messageRepoArtifactStore adapts interfaces.MessageRepository to the
// SessionArtifactStore contract expected by ArtifactCollector. It is a thin
// projection: KnownArtifacts is documented as best-effort, so we forward
// repo errors verbatim and let the collector decide how to degrade.
type messageRepoArtifactStore struct {
repo interfaces.MessageRepository
}
// NewMessageRepoArtifactStore wraps a MessageRepository so ArtifactCollector
// can build its de-duplication set from every prior message of the session.
func NewMessageRepoArtifactStore(repo interfaces.MessageRepository) SessionArtifactStore {
return &messageRepoArtifactStore{repo: repo}
}
// KnownArtifacts satisfies SessionArtifactStore.
func (s *messageRepoArtifactStore) KnownArtifacts(
ctx context.Context, sessionID string,
) ([]types.MessageArtifact, error) {
if s == nil || s.repo == nil || sessionID == "" {
return nil, nil
}
arts, err := s.repo.GetSessionArtifacts(ctx, sessionID)
if err != nil {
return nil, err
}
return arts, nil
}

View File

@ -0,0 +1,527 @@
package service
import (
"context"
stderrors "errors"
"io"
"mime/multipart"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// -----------------------------------------------------------------------------
// Test doubles
// -----------------------------------------------------------------------------
// fakeSandboxSource is an in-memory stand-in for SessionBoundManager that
// records the calls the collector makes and returns pre-programmed
// responses. Concrete tests populate `entries` (one map per session) and
// `contents` (one map per absolute path).
type fakeSandboxSource struct {
entries map[string][]sandbox.RemoteDirEntry
contents map[string][]byte
listErr error
readErr error
listCalls int
readCalls []string
}
func (f *fakeSandboxSource) ListSessionFiles(_ context.Context, sessionID, _ string) ([]sandbox.RemoteDirEntry, error) {
f.listCalls++
if f.listErr != nil {
return nil, f.listErr
}
return f.entries[sessionID], nil
}
func (f *fakeSandboxSource) ReadSessionFile(_ context.Context, _ string, path string) ([]byte, error) {
f.readCalls = append(f.readCalls, path)
if f.readErr != nil {
return nil, f.readErr
}
if data, ok := f.contents[path]; ok {
return data, nil
}
return nil, stderrors.New("fake source: not found: " + path)
}
// fakeStore lets a test declare which (path, mtime) tuples the collector
// should treat as already recorded.
type fakeStore struct {
prev []types.MessageArtifact
err error
}
func (s *fakeStore) KnownArtifacts(_ context.Context, _ string) ([]types.MessageArtifact, error) {
return s.prev, s.err
}
// fakeFileService captures uploads and returns a deterministic provider URL.
// Only SaveBytes is exercised by the collector; the other methods are
// implemented to satisfy interfaces.FileService but panic on use so a
// regression that starts calling them doesn't fail silently.
type fakeFileService struct {
saved map[string][]byte
saveErr error
seq int
tenantIDs []uint64
}
func (f *fakeFileService) CheckConnectivity(_ context.Context) error { return nil }
func (f *fakeFileService) SaveFile(_ context.Context, _ *multipart.FileHeader, _ uint64, _ string) (string, error) {
panic("SaveFile should not be called by ArtifactCollector")
}
func (f *fakeFileService) SaveBytes(_ context.Context, data []byte, tenantID uint64, fileName string, _ bool) (string, error) {
if f.saveErr != nil {
return "", f.saveErr
}
if f.saved == nil {
f.saved = map[string][]byte{}
}
f.seq++
key := "fake://tenant-" + fileName
f.saved[key] = append([]byte(nil), data...)
f.tenantIDs = append(f.tenantIDs, tenantID)
return key, nil
}
func (f *fakeFileService) GetFile(_ context.Context, _ string) (io.ReadCloser, error) {
panic("GetFile should not be called by ArtifactCollector")
}
func (f *fakeFileService) GetFileURL(_ context.Context, _ string) (string, error) {
panic("GetFileURL should not be called by ArtifactCollector")
}
func (f *fakeFileService) DeleteFile(_ context.Context, _ string) error { return nil }
func (f *fakeFileService) CopyFile(_ context.Context, _ string, _ uint64, _ string) (string, error) {
panic("CopyFile should not be called by ArtifactCollector")
}
// resourceRefFileService is a fileService whose SaveBytes returns a valid
// resource:// reference, so the collector's binding path is exercised.
type resourceRefFileService struct {
fakeFileService
handle string
}
func (f *resourceRefFileService) SaveBytes(_ context.Context, data []byte, tenantID uint64, fileName string, _ bool) (string, error) {
if f.saved == nil {
f.saved = map[string][]byte{}
}
f.seq++
ref := types.BuildResourcePath(f.handle)
f.saved[ref] = append([]byte(nil), data...)
f.tenantIDs = append(f.tenantIDs, tenantID)
return ref, nil
}
// bindCall records one Bind invocation for assertions.
type bindCall struct {
ref string
ownerType string
ownerID string
relation string
}
// fakeCatalog captures Bind calls; every other ResourceCatalog method is a
// no-op stub because the collector only ever calls Bind.
type fakeCatalog struct {
binds []bindCall
bindErr error
}
func (c *fakeCatalog) Register(context.Context, uint64, string, interfaces.ResourceRegistration) (string, error) {
return "", nil
}
func (c *fakeCatalog) Resolve(context.Context, string) (*types.StoredResource, error) {
return nil, nil
}
func (c *fakeCatalog) ResolvePath(_ context.Context, v string) (string, *types.StoredResource, error) {
return v, nil, nil
}
func (c *fakeCatalog) Bind(_ context.Context, ref, ownerType, ownerID, relation string) error {
c.binds = append(c.binds, bindCall{ref, ownerType, ownerID, relation})
return c.bindErr
}
func (c *fakeCatalog) MarkDeleted(context.Context, string) error { return nil }
func (c *fakeCatalog) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
return "", nil
}
func (c *fakeCatalog) ResolveAccessGrant(context.Context, string) (*types.StoredResource, error) {
return nil, nil
}
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
func newTestCollector(src *fakeSandboxSource, store *fakeStore, fs *fakeFileService, max int64) *ArtifactCollector {
// catalog is nil here: these tests use a fakeFileService that returns raw
// "fake://" paths, so no resource binding is attempted. Binding behaviour
// is covered separately in TestArtifactCollector_BindsResourceToMessage.
return NewArtifactCollector(src, fs, store, nil, ArtifactCollectorConfig{MaxFileBytes: max})
}
func TestArtifactCollector_CollectsNewFiles(t *testing.T) {
ctx := context.Background()
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
{Name: "summary.txt", Path: "/workspace/output/summary.txt", Type: sandbox.RemoteEntryFile, Size: 3, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX"),
"/workspace/output/summary.txt": []byte("hey"),
},
}
store := &fakeStore{}
fs := &fakeFileService{}
c := newTestCollector(src, store, fs, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 2 {
t.Fatalf("Collect() len = %d, want 2 (%+v)", len(got), got)
}
// Files must be uploaded with the tenant ID passed by the caller.
for _, tID := range fs.tenantIDs {
if tID != 42 {
t.Fatalf("SaveBytes tenant = %d, want 42", tID)
}
}
// Both files must have populated URL + FileType + FileSize.
for _, art := range got {
if art.URL == "" {
t.Fatalf("artifact URL empty: %+v", art)
}
if art.FileType == "" {
t.Fatalf("artifact FileType empty: %+v", art)
}
if art.FileSize == 0 {
t.Fatalf("artifact FileSize zero: %+v", art)
}
}
}
func TestArtifactCollector_SkipsAlreadyKnown(t *testing.T) {
ctx := context.Background()
mod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX"),
},
}
store := &fakeStore{prev: []types.MessageArtifact{
{SourcePath: "/workspace/output/report.pptx", ModTime: mod},
}}
fs := &fakeFileService{}
c := newTestCollector(src, store, fs, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0 (dedupe should have kicked in)", len(got))
}
if len(fs.saved) != 0 {
t.Fatalf("SaveBytes should not have been called; saved=%v", fs.saved)
}
if len(src.readCalls) != 0 {
t.Fatalf("ReadSessionFile should not have been called; readCalls=%v", src.readCalls)
}
}
func TestArtifactCollector_ReattachesOnMtimeChange(t *testing.T) {
ctx := context.Background()
oldMod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
// Same path as the known set, but a *newer* mtime — must be re-attached.
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:21:00Z")},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX"),
},
}
store := &fakeStore{prev: []types.MessageArtifact{
{SourcePath: "/workspace/output/report.pptx", ModTime: oldMod},
}}
fs := &fakeFileService{}
c := newTestCollector(src, store, fs, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("Collect() len = %d, want 1 (mtime-change should re-attach)", len(got))
}
if len(fs.saved) != 1 {
t.Fatalf("SaveBytes calls = %d, want 1", len(fs.saved))
}
}
func TestArtifactCollector_SkipsOversize(t *testing.T) {
ctx := context.Background()
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "huge.bin", Path: "/workspace/output/huge.bin", Type: sandbox.RemoteEntryFile, Size: 1024, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
{Name: "ok.txt", Path: "/workspace/output/ok.txt", Type: sandbox.RemoteEntryFile, Size: 3, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
},
},
contents: map[string][]byte{
"/workspace/output/huge.bin": bytesN(2048),
"/workspace/output/ok.txt": []byte("hey"),
},
}
fs := &fakeFileService{}
c := newTestCollector(src, &fakeStore{}, fs, 100)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("Collect() len = %d, want 1 (oversize file must be skipped)", len(got))
}
if got[0].FileName != "ok.txt" {
t.Fatalf("Collect() kept the wrong file: %+v", got[0])
}
}
func TestArtifactCollector_SkipsOversizeAfterRead(t *testing.T) {
// Envd can report a stale size while the file grows; the collector must
// enforce the cap against the actual bytes too.
ctx := context.Background()
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "lying.bin", Path: "/workspace/output/lying.bin", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
},
},
contents: map[string][]byte{
"/workspace/output/lying.bin": bytesN(2048),
},
}
fs := &fakeFileService{}
c := newTestCollector(src, &fakeStore{}, fs, 100)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0", len(got))
}
}
func TestArtifactCollector_EmptyWhenNoEntries(t *testing.T) {
ctx := context.Background()
src := &fakeSandboxSource{}
c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0", len(got))
}
}
func TestArtifactCollector_EmptyWhenNoSessionID(t *testing.T) {
// The collector treats empty session ID as "nothing to do" — the design
// spec forbids sandbox lookups for chat-only sessions.
ctx := context.Background()
src := &fakeSandboxSource{}
c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
got, err := c.Collect(ctx, "", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0", len(got))
}
if src.listCalls != 0 {
t.Fatalf("expected 0 list calls for empty session id, got %d", src.listCalls)
}
}
func TestArtifactCollector_ListErrorDegrades(t *testing.T) {
ctx := context.Background()
src := &fakeSandboxSource{listErr: stderrors.New("envd timeout")}
c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v (should degrade gracefully)", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0", len(got))
}
}
func TestArtifactCollector_UploadFailureIsPerFile(t *testing.T) {
// A single failed upload must NOT abort the whole batch — the other
// files should still be persisted, matching the best-effort contract.
ctx := context.Background()
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "a.txt", Path: "/workspace/output/a.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
{Name: "b.txt", Path: "/workspace/output/b.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
},
},
contents: map[string][]byte{
"/workspace/output/a.txt": []byte("a"),
"/workspace/output/b.txt": []byte("b"),
},
}
// FileService fails on every call — both files should be skipped without
// propagating an error.
fs := &fakeFileService{saveErr: stderrors.New("s3 dead")}
c := newTestCollector(src, &fakeStore{}, fs, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v (want best-effort)", err)
}
if len(got) != 0 {
t.Fatalf("Collect() len = %d, want 0 (all uploads failed)", len(got))
}
}
func TestArtifactCollector_FiltersDirectories(t *testing.T) {
ctx := context.Background()
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
// The production ListSessionFiles never yields dirs, but the
// collector must defensively skip anything with Type=="dir"
// so alternate SandboxArtifactSource impls stay safe.
{Name: "sub", Path: "/workspace/output/sub", Type: sandbox.RemoteEntryDir, Size: 0, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
{Name: "a.txt", Path: "/workspace/output/a.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:34Z")},
},
},
contents: map[string][]byte{
"/workspace/output/a.txt": []byte("a"),
},
}
c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
got, err := c.Collect(ctx, "sess-1", "msg-1", 42, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("Collect() len = %d, want 1 (dir must be skipped)", len(got))
}
if !strings.HasSuffix(got[0].SourcePath, "a.txt") {
t.Fatalf("wrong file kept: %+v", got[0])
}
}
func TestArtifactCollector_BindsResourceToMessage(t *testing.T) {
ctx := context.Background()
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "report.pptx", Path: "/workspace/output/report.pptx", Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
},
},
contents: map[string][]byte{
"/workspace/output/report.pptx": []byte("PPTX"),
},
}
// 22-char handle so BuildResourcePath yields a valid resource:// ref.
fs := &resourceRefFileService{handle: "abcdefghijklmnopqrstuv"}
cat := &fakeCatalog{}
c := NewArtifactCollector(src, fs, &fakeStore{}, cat, ArtifactCollectorConfig{MaxFileBytes: 1 << 20})
got, err := c.Collect(ctx, "sess-1", "msg-42", 7, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("Collect() len = %d, want 1", len(got))
}
if len(cat.binds) != 1 {
t.Fatalf("Bind calls = %d, want 1 (%+v)", len(cat.binds), cat.binds)
}
b := cat.binds[0]
if b.ownerType != "message" || b.ownerID != "msg-42" || b.relation != "artifact" {
t.Fatalf("unexpected binding: %+v", b)
}
if _, ok := types.ParseResourcePath(b.ref); !ok {
t.Fatalf("binding ref is not a resource reference: %q", b.ref)
}
}
func TestArtifactCollector_BindFailureDoesNotDropArtifact(t *testing.T) {
ctx := context.Background()
src := &fakeSandboxSource{
entries: map[string][]sandbox.RemoteDirEntry{
"sess-1": {
{Name: "a.txt", Path: "/workspace/output/a.txt", Type: sandbox.RemoteEntryFile, Size: 1, ModTime: mustParseTime("2026-07-10T10:20:33Z")},
},
},
contents: map[string][]byte{"/workspace/output/a.txt": []byte("a")},
}
fs := &resourceRefFileService{handle: "abcdefghijklmnopqrstuv"}
cat := &fakeCatalog{bindErr: stderrors.New("db down")}
c := NewArtifactCollector(src, fs, &fakeStore{}, cat, ArtifactCollectorConfig{MaxFileBytes: 1 << 20})
got, err := c.Collect(ctx, "sess-1", "msg-1", 7, "/workspace/output")
if err != nil {
t.Fatalf("Collect() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("Collect() len = %d, want 1 (bind failure must not drop the artifact)", len(got))
}
}
// mustParseTime parses an RFC3339 timestamp for test data. It fails the
// program on error because test fixtures should never contain malformed
// timestamps.
func mustParseTime(raw string) time.Time {
t, err := time.Parse(time.RFC3339Nano, raw)
if err != nil {
t, err = time.Parse(time.RFC3339, raw)
}
if err != nil {
panic("mustParseTime: " + err.Error())
}
return t
}
// bytesN returns a byte slice of length n filled with 'x'. Kept local to
// avoid pulling in a dependency; matches "generate N bytes" test helpers
// elsewhere in the codebase.
func bytesN(n int) []byte {
b := make([]byte, n)
for i := range b {
b[i] = 'x'
}
return b
}

View File

@ -479,6 +479,19 @@ func (s *messageService) GetChatHistoryKBStats(ctx context.Context) (*types.Chat
return stats, nil
}
// GetSessionArtifacts returns every skill-produced artifact recorded against
// any assistant message of the session. Thin pass-through to the repository:
// the collector and session cleanup both need it, and centralising it here
// keeps tests able to inject a stub MessageService.
func (s *messageService) GetSessionArtifacts(
ctx context.Context, sessionID string,
) (types.MessageArtifacts, error) {
if sessionID == "" {
return types.MessageArtifacts{}, nil
}
return s.messageRepo.GetSessionArtifacts(ctx, sessionID)
}
// ─────────────────────────────────────────────────────────────────────────────
// Message Search (Hybrid: Keyword + KB Vector Search)
// ─────────────────────────────────────────────────────────────────────────────

View File

@ -71,6 +71,12 @@ func (s *stubAgentRepoForModelDelete) DeleteAgent(context.Context, string, uint6
func (s *stubAgentRepoForModelDelete) CountByModelID(context.Context, uint64, string) (int64, error) {
return s.count, nil
}
func (s *stubAgentRepoForModelDelete) CountBySandboxConfigID(context.Context, uint64, string) (int64, error) {
return 0, nil
}
func (s *stubAgentRepoForModelDelete) ListNamesBySandboxConfigID(context.Context, uint64, string) ([]string, error) {
return nil, nil
}
type stubModelRepoForDelete struct {
model *types.Model

View File

@ -16,6 +16,7 @@ import (
"github.com/google/uuid"
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
"github.com/Tencent/WeKnora/internal/sandbox"
)
func sessionUserIDFromContext(ctx context.Context) string {
@ -123,6 +124,10 @@ type sessionService struct {
webSearchProviderRepo interfaces.WebSearchProviderRepository // Repository for web search provider entities
kbShareService interfaces.KBShareService // Service for KB sharing operations
suggestionRepo interfaces.MessageSuggestionRepository
sandboxMgr sandbox.Manager // Default sandbox backend; used to reclaim per-session MicroVMs on delete
sandboxResolver sandbox.TenantSandboxResolver
sandboxPinner *SessionSandboxPinner
sandboxPolicy WorkspaceSandboxPolicy
}
// NewSessionService creates a new session service instance with all required dependencies
@ -140,6 +145,10 @@ func NewSessionService(cfg *config.Config,
webSearchProviderRepo interfaces.WebSearchProviderRepository,
kbShareService interfaces.KBShareService,
suggestionRepo interfaces.MessageSuggestionRepository,
sandboxMgr sandbox.Manager,
sandboxResolver sandbox.TenantSandboxResolver,
sandboxPinner *SessionSandboxPinner,
sandboxPolicy WorkspaceSandboxPolicy,
) interfaces.SessionService {
return &sessionService{
cfg: cfg,
@ -156,6 +165,10 @@ func NewSessionService(cfg *config.Config,
webSearchProviderRepo: webSearchProviderRepo,
kbShareService: kbShareService,
suggestionRepo: suggestionRepo,
sandboxMgr: sandboxMgr,
sandboxResolver: sandboxResolver,
sandboxPinner: sandboxPinner,
sandboxPolicy: sandboxPolicy,
}
}
@ -470,11 +483,27 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
}
}()
// NOTE: Skill-generated artifact blobs are intentionally NOT purged here.
// Their lifecycle mirrors messages, which are soft-deleted (deleted_at
// timestamp) rather than physically removed. Hard-deleting the blobs on a
// soft session delete would (a) diverge from message semantics, (b) make
// any future "restore soft-deleted session" flow silently broken, and (c)
// leave 404s in the download endpoint if the message row is ever surfaced
// again. A dedicated GC job or explicit hard-delete API is the right
// place to reclaim storage — not this soft-delete path.
// Cleanup temporary KB stored in Redis for this session
if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", id, err)
}
if s.suggestionRepo != nil {
if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, id); err != nil {
logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", id, err)
}
}
s.destroyBoundSandbox(ctx, id)
// Delete session from repository
rows, err := s.sessionRepo.Delete(ctx, tenantID, userID, id)
if err != nil {
@ -487,11 +516,6 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
if rows == 0 {
return apperrors.ErrSessionNotFound
}
if s.suggestionRepo != nil {
if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, id); err != nil {
logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", id, err)
}
}
return nil
}
@ -539,6 +563,13 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", id, err)
}
// Artifact blobs are kept alongside soft-deleted messages — see
// DeleteSession for the rationale.
}
// Tear down sandboxes while session rows (and pins) are still readable.
for _, id := range visibleIDs {
s.destroyBoundSandbox(ctx, id)
}
// Batch delete sessions from repository
@ -589,6 +620,15 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, session.ID); err != nil {
logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", session.ID, err)
}
// Artifact blobs are kept alongside soft-deleted messages — see
// DeleteSession for the rationale.
}
}
// Tear down sandboxes while session rows (and pins) are still readable.
if sessions != nil {
for _, session := range sessions {
s.destroyBoundSandbox(ctx, session.ID)
}
}
@ -610,6 +650,60 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
return nil
}
// destroyBoundSandbox tears down the sandbox MicroVM bound to sessionID, if
// the configured sandbox backend supports session-scoped instances.
//
// Only SessionBoundManager (the CubeSandbox backend) implements the
// DestroySession method. For Docker/Local/Disabled backends the type assertion
// fails and the call is a no-op — those backends are stateless per Execute
// and hold no resources keyed on session ID.
//
// Errors are logged but never propagated: sandbox teardown must not block
// session deletion. Call this while the session row is still live so the
// sandbox_config_id pin resolves to the correct named backend.
func (s *sessionService) destroyBoundSandbox(ctx context.Context, sessionID string) {
if sessionID == "" {
return
}
// Resolve the workspace's own manager: the sandbox to release lives on
// whichever backend that workspace is configured for, not necessarily the
// process-wide default.
tenantID, _ := types.TenantIDFromContext(ctx)
configID, err := sandboxConfigForExistingSandbox(ctx, s.sandboxPinner, sessionID)
if err != nil {
logger.Warnf(ctx, "Failed to read sandbox pin for session %s cleanup: %v", sessionID, err)
return
}
// An empty pin normally means there is nothing to destroy, but sessions
// whose sandbox predates the pin column also read as empty. Falling through
// to the default manager keeps those reachable: DestroySession is a cheap
// binding lookup that no-ops when the session truly has no sandbox, whereas
// skipping would abandon a paused instance that keeps billing.
mgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy)
if err != nil {
logger.Warnf(ctx, "Failed to resolve sandbox for session %s cleanup: %v", sessionID, err)
return
}
if mgr == nil {
return
}
destroyer, ok := mgr.(interface {
DestroySession(context.Context, string) error
})
if !ok {
return
}
if err := destroyer.DestroySession(ctx, sessionID); err != nil {
logger.Warnf(ctx, "Failed to destroy sandbox for session %s: %v", sessionID, err)
return
}
if s.sandboxPinner != nil {
if err := s.sandboxPinner.Clear(ctx, sessionID); err != nil {
logger.Warnf(ctx, "Failed to clear sandbox pin for session %s: %v", sessionID, err)
}
}
}
// GenerateTitle generates a title for the current conversation content
// modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model)
func (s *sessionService) GenerateTitle(ctx context.Context,

View File

@ -24,6 +24,9 @@ func (s *sessionService) AgentQA(
eventBus *event.EventBus,
) error {
sessionID := req.Session.ID
// Propagate the session ID so stateful sandbox backends (CubeSandbox) can
// bind script execution to a per-session MicroVM instance.
ctx = types.WithSessionID(ctx, sessionID)
sessionJSON, err := json.Marshal(req.Session)
if err != nil {
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
@ -140,6 +143,36 @@ func (s *sessionService) AgentQA(
llmContext = []chat.Message{}
}
// Reconcile all durable session attachments into the session's remote
// sandbox before the model can request shell or skill execution. The
// durable storage URL — not the ephemeral sandbox path — remains the
// source of truth. Gated on the sandbox manager advertising a session
// filesystem capability so provider-neutral wiring (Cube today, E2B
// tomorrow) drops in without touching this call site.
var stagedAttachments []stagedSessionAttachment
stager, ok := s.agentService.(sessionAttachmentStager)
if !ok {
return errors.New("agent service does not support session attachment staging")
}
// Probe the backend this session's sandbox actually runs on. Gating on the
// process-wide manager instead would skip staging whenever the deployment
// default is docker/local but the agent selected a named Cube/E2B config —
// the tools would still run remotely, against an empty /workspace/input.
inputStore, storeErr := stager.sessionSandboxInputStore(ctx, sessionID, agentConfig.SandboxConfigID)
if storeErr != nil {
return fmt.Errorf("resolve sandbox file store for session %s: %w", sessionID, storeErr)
}
if inputStore != nil {
sessionAttachments, loadErr := s.messageRepo.GetSessionAttachments(ctx, sessionID)
if loadErr != nil {
return fmt.Errorf("load session attachments for sandbox staging: %w", loadErr)
}
stagedAttachments, err = stager.stageSessionAttachments(ctx, sessionID, agentConfig.SandboxConfigID, sessionAttachments)
if err != nil {
return fmt.Errorf("restore session attachments into sandbox: %w", err)
}
}
// Create agent engine with EventBus
logger.Info(ctx, "Creating agent engine")
engine, err := s.agentService.CreateAgentEngine(
@ -183,6 +216,10 @@ func (s *sessionService) AgentQA(
agentQuery += req.Attachments.BuildPrompt()
logger.Infof(ctx, "Appended %d attachment(s) to agent query", len(req.Attachments))
}
if manifest := buildSandboxAttachmentsPrompt(stagedAttachments); manifest != "" {
agentQuery += manifest
logger.Infof(ctx, "Appended %d staged sandbox attachment path(s) to agent query", len(stagedAttachments))
}
// Scope envelopes (runtime_context / must_use) are injected per LLM call inside
// the agent engine only; we intentionally do not persist them on user messages
@ -499,6 +536,7 @@ func (s *sessionService) configureSkillsFromAgent(
if customAgent == nil {
return
}
agentConfig.SandboxConfigID = customAgent.Config.SandboxConfigID
// When sandbox is disabled, skills cannot be enabled (no script execution environment)
sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")
if sandboxMode == "" || sandboxMode == "disabled" {

View File

@ -0,0 +1,235 @@
package service
import (
"context"
"crypto/sha256"
"fmt"
"io"
"path"
"sort"
"strings"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
type stagedSessionAttachment struct {
Name string
FileType string
Size int64
Path string
}
// sessionSandboxFileStore returns the manager's effective session filesystem
// capability, or nil when the backend cannot support it. Centralised so
// callers never resurrect a Cube-specific type check.
func sessionSandboxFileStore(mgr sandbox.Manager) sandbox.SessionFileStore {
provider, ok := mgr.(sandbox.SessionCapabilityProvider)
if !ok || provider == nil {
return nil
}
return provider.SessionFileStore()
}
// sessionSandboxShellExecutor is the shell-execution counterpart of
// sessionSandboxFileStore.
func sessionSandboxShellExecutor(mgr sandbox.Manager) sandbox.SessionShellExecutor {
provider, ok := mgr.(sandbox.SessionCapabilityProvider)
if !ok || provider == nil {
return nil
}
return provider.SessionShellExecutor()
}
// sessionAttachmentStager is the agentService surface the QA pipeline needs to
// stage attachments. Declared as a named interface so the runtime type
// assertion in session_agent_qa.go has one definition to drift against.
type sessionAttachmentStager interface {
sessionSandboxInputStore(
ctx context.Context, sessionID, agentSandboxConfigID string,
) (sandbox.SessionFileStore, error)
stageSessionAttachments(
ctx context.Context, sessionID, agentSandboxConfigID string,
attachments types.MessageAttachments,
) ([]stagedSessionAttachment, error)
}
// sessionSandboxInputStore resolves the session filesystem capability of the
// backend this session's sandbox actually runs on.
//
// Callers must gate staging on this rather than on the process-wide manager: a
// workspace can select a named Cube/E2B config while the deployment default is
// docker/local, and in that combination the agent still registers shell/skill
// tools against the remote sandbox, so its attachments have to be staged too.
func (s *agentService) sessionSandboxInputStore(
ctx context.Context,
sessionID string,
agentSandboxConfigID string,
) (sandbox.SessionFileStore, error) {
if s == nil {
return nil, nil
}
tenantID, _ := types.TenantIDFromContext(ctx)
configID, err := sandboxConfigForExecution(ctx, s.sandboxPinner, sessionID, agentSandboxConfigID)
if err != nil {
return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)
}
mgr, err := resolveTenantSandboxForConfig(
ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy,
)
if err != nil {
return nil, err
}
return sessionSandboxFileStore(mgr), nil
}
// stageSessionAttachments reconciles /workspace/input with the durable
// attachment inventory. It is gated on the sandbox manager advertising a
// session filesystem capability; other backends retain prompt-extracted
// attachment content and never receive host file paths.
func (s *agentService) stageSessionAttachments(
ctx context.Context,
sessionID string,
agentSandboxConfigID string,
attachments types.MessageAttachments,
) ([]stagedSessionAttachment, error) {
if s == nil {
return nil, nil
}
store, err := s.sessionSandboxInputStore(ctx, sessionID, agentSandboxConfigID)
if err != nil {
return nil, err
}
if store == nil {
return nil, nil
}
if s.fileService == nil && len(attachments) > 0 {
return nil, fmt.Errorf("file service is unavailable for session input staging")
}
attachments = deduplicateSessionAttachments(attachments)
existingEntries, err := store.ListSessionFiles(ctx, sessionID, sandbox.SessionInputRoot)
if err != nil {
return nil, fmt.Errorf("list staged session inputs: %w", err)
}
existing := make(map[string]sandbox.RemoteDirEntry, len(existingEntries))
for _, entry := range existingEntries {
existing[path.Clean(entry.Path)] = entry
}
desired := make(map[string]struct{}, len(attachments))
staged := make([]stagedSessionAttachment, 0, len(attachments))
maxBytes := int64(secutils.GetMaxFileSizeMB()) * 1024 * 1024
for _, attachment := range attachments {
remotePath, pathErr := sandboxAttachmentPath(attachment)
if pathErr != nil {
return nil, pathErr
}
desired[remotePath] = struct{}{}
entry, present := existing[remotePath]
if !present || attachment.FileSize <= 0 || entry.Size != attachment.FileSize {
reader, getErr := s.fileService.GetFile(ctx, attachment.URL)
if getErr != nil {
return nil, fmt.Errorf("open attachment %q: %w", attachment.FileName, getErr)
}
content, readErr := io.ReadAll(io.LimitReader(reader, maxBytes+1))
closeErr := reader.Close()
if readErr != nil {
return nil, fmt.Errorf("read attachment %q: %w", attachment.FileName, readErr)
}
if closeErr != nil {
return nil, fmt.Errorf("close attachment %q: %w", attachment.FileName, closeErr)
}
if int64(len(content)) > maxBytes {
return nil, fmt.Errorf("attachment %q exceeds sandbox staging limit of %d bytes", attachment.FileName, maxBytes)
}
if writeErr := store.WriteSessionInputFile(ctx, sessionID, remotePath, content); writeErr != nil {
return nil, fmt.Errorf("stage attachment %q: %w", attachment.FileName, writeErr)
}
attachment.FileSize = int64(len(content))
}
staged = append(staged, stagedSessionAttachment{
Name: attachment.FileName,
FileType: attachment.FileType,
Size: attachment.FileSize,
Path: remotePath,
})
}
// Remove inputs whose durable message attachment no longer exists.
for filePath := range existing {
if _, keep := desired[filePath]; !keep {
if err := store.RemoveSessionInputPath(ctx, sessionID, filePath); err != nil {
return nil, fmt.Errorf("remove stale session input %s: %w", filePath, err)
}
}
}
sort.SliceStable(staged, func(i, j int) bool { return staged[i].Path < staged[j].Path })
return staged, nil
}
func deduplicateSessionAttachments(attachments types.MessageAttachments) types.MessageAttachments {
seen := make(map[string]struct{}, len(attachments))
out := make(types.MessageAttachments, 0, len(attachments))
for _, attachment := range attachments {
url := strings.TrimSpace(attachment.URL)
if url == "" {
continue
}
if _, exists := seen[url]; exists {
continue
}
seen[url] = struct{}{}
out = append(out, attachment)
}
return out
}
func sandboxAttachmentPath(attachment types.MessageAttachment) (string, error) {
url := strings.TrimSpace(attachment.URL)
if url == "" {
return "", fmt.Errorf("attachment %q has no durable storage URL", attachment.FileName)
}
fileName, err := secutils.SafeFileName(attachment.FileName)
if err != nil {
return "", fmt.Errorf("unsafe attachment filename %q: %w", attachment.FileName, err)
}
sum := sha256.Sum256([]byte(url))
return path.Join(sandbox.SessionInputRoot, fmt.Sprintf("%x", sum[:6]), fileName), nil
}
func buildSandboxAttachmentsPrompt(attachments []stagedSessionAttachment) string {
if len(attachments) == 0 {
return ""
}
var b strings.Builder
b.WriteString("\n\n<sandbox_attachments root=\"/workspace/input\">\n")
for _, attachment := range attachments {
fmt.Fprintf(
&b,
" <file name=\"%s\" type=\"%s\" size_bytes=\"%d\" path=\"%s\" />\n",
escapeAttachmentXML(attachment.Name),
escapeAttachmentXML(attachment.FileType),
attachment.Size,
escapeAttachmentXML(attachment.Path),
)
}
b.WriteString(" <instruction>Use these absolute paths as read-only inputs for shell commands or skill script arguments. Write generated files only under $WEKNORA_SKILL_OUTPUT_DIR.</instruction>\n")
b.WriteString("</sandbox_attachments>")
return b.String()
}
func escapeAttachmentXML(value string) string {
replacer := strings.NewReplacer(
"&", "&amp;",
"<", "&lt;",
">", "&gt;",
"\"", "&quot;",
"'", "&apos;",
)
return replacer.Replace(value)
}

View File

@ -0,0 +1,179 @@
package service
import (
"bytes"
"context"
"io"
"mime/multipart"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type stagingFileService struct {
files map[string][]byte
getCalls map[string]int
}
func (f *stagingFileService) CheckConnectivity(context.Context) error { return nil }
func (f *stagingFileService) SaveFile(context.Context, *multipart.FileHeader, uint64, string) (string, error) {
panic("unexpected SaveFile")
}
func (f *stagingFileService) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) {
panic("unexpected SaveBytes")
}
func (f *stagingFileService) GetFile(_ context.Context, filePath string) (io.ReadCloser, error) {
if f.getCalls == nil {
f.getCalls = make(map[string]int)
}
f.getCalls[filePath]++
return io.NopCloser(bytes.NewReader(f.files[filePath])), nil
}
func (f *stagingFileService) GetFileURL(context.Context, string) (string, error) {
panic("unexpected GetFileURL")
}
func (f *stagingFileService) DeleteFile(context.Context, string) error { return nil }
func (f *stagingFileService) CopyFile(context.Context, string, uint64, string) (string, error) {
panic("unexpected CopyFile")
}
// stagingSandboxManager is a test double that satisfies both the Manager
// contract and the SessionCapabilityProvider capability accessor. It stores
// in-memory files so a staging test can round-trip attachments without a
// real sandbox.
type stagingSandboxManager struct {
sandboxType sandbox.SandboxType
files map[string][]byte
writes []string
removes []string
// disableFiles lets a test simulate a manager that advertises no
// session filesystem capability (e.g. Local fallback engaged).
disableFiles bool
}
func (m *stagingSandboxManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
panic("unexpected Execute")
}
func (m *stagingSandboxManager) Cleanup(context.Context) error { return nil }
func (m *stagingSandboxManager) GetSandbox() sandbox.Sandbox { return nil }
func (m *stagingSandboxManager) GetType() sandbox.SandboxType { return m.sandboxType }
func (m *stagingSandboxManager) SessionShellExecutor() sandbox.SessionShellExecutor { return nil }
func (m *stagingSandboxManager) SessionFileStore() sandbox.SessionFileStore {
if m.disableFiles {
return nil
}
return m
}
func (m *stagingSandboxManager) EnsureSessionDir(context.Context, string, string) error {
return nil
}
func (m *stagingSandboxManager) StatSessionFile(context.Context, string, string) (*sandbox.RemoteStatEntry, error) {
panic("unexpected StatSessionFile")
}
func (m *stagingSandboxManager) ReadSessionFile(context.Context, string, string) ([]byte, error) {
panic("unexpected ReadSessionFile")
}
func (m *stagingSandboxManager) ListSessionFiles(context.Context, string, string) ([]sandbox.RemoteDirEntry, error) {
entries := make([]sandbox.RemoteDirEntry, 0, len(m.files))
for filePath, content := range m.files {
entries = append(entries, sandbox.RemoteDirEntry{Path: filePath, Size: int64(len(content)), Type: sandbox.RemoteEntryFile})
}
return entries, nil
}
func (m *stagingSandboxManager) WriteSessionInputFile(_ context.Context, _ string, filePath string, content []byte) error {
if m.files == nil {
m.files = make(map[string][]byte)
}
m.files[filePath] = append([]byte(nil), content...)
m.writes = append(m.writes, filePath)
return nil
}
func (m *stagingSandboxManager) RemoveSessionInputPath(_ context.Context, _ string, targetPath string) error {
for filePath := range m.files {
if filePath == targetPath || strings.HasPrefix(filePath, targetPath+"/") {
delete(m.files, filePath)
}
}
m.removes = append(m.removes, targetPath)
return nil
}
func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {
t.Setenv("WEKNORA_SANDBOX_MODE", "cube")
attachment := types.MessageAttachment{
URL: "local://tenant/attachment-1",
FileName: "report.pdf",
FileType: ".pdf",
FileSize: 7,
}
remotePath, err := sandboxAttachmentPath(attachment)
require.NoError(t, err)
stalePath := sandbox.SessionInputRoot + "/stale/old.txt"
manager := &stagingSandboxManager{
sandboxType: sandbox.SandboxTypeCube,
files: map[string][]byte{stalePath: []byte("old")},
}
fileService := &stagingFileService{
files: map[string][]byte{attachment.URL: []byte("content")},
}
service := &agentService{sandboxMgr: manager, fileService: fileService}
staged, err := service.stageSessionAttachments(
context.Background(),
"session-1",
"",
types.MessageAttachments{attachment, attachment},
)
require.NoError(t, err)
require.Len(t, staged, 1)
assert.Equal(t, remotePath, staged[0].Path)
assert.Equal(t, []string{remotePath}, manager.writes)
assert.Equal(t, 1, fileService.getCalls[attachment.URL])
assert.NotEmpty(t, manager.removes)
assert.NotContains(t, manager.files, stalePath)
// The second reconciliation sees the same path and size and avoids storage IO.
_, err = service.stageSessionAttachments(context.Background(), "session-1", "", types.MessageAttachments{attachment})
require.NoError(t, err)
assert.Equal(t, 1, fileService.getCalls[attachment.URL])
}
func TestStageSessionAttachmentsSkipsWhenNoFilesystemCapability(t *testing.T) {
t.Setenv("WEKNORA_SANDBOX_MODE", "local")
// disableFiles=true simulates any manager without a session filesystem
// capability (Local/Docker/Disabled DefaultManager, or a
// SessionBoundManager whose remote provider fell back to Local).
manager := &stagingSandboxManager{
sandboxType: sandbox.SandboxTypeLocal,
disableFiles: true,
}
service := &agentService{sandboxMgr: manager, fileService: &stagingFileService{}}
staged, err := service.stageSessionAttachments(context.Background(), "session-1", "", types.MessageAttachments{{
URL: "local://tenant/file", FileName: "file.txt",
}})
require.NoError(t, err)
assert.Empty(t, staged)
assert.Empty(t, manager.writes)
}
func TestBuildSandboxAttachmentsPromptEscapesMetadata(t *testing.T) {
prompt := buildSandboxAttachmentsPrompt([]stagedSessionAttachment{{
Name: "a<&>.txt", FileType: ".txt", Size: 3, Path: "/workspace/input/hash/a.txt",
}})
assert.Contains(t, prompt, `name="a&lt;&amp;&gt;.txt"`)
assert.Contains(t, prompt, `path="/workspace/input/hash/a.txt"`)
assert.Contains(t, prompt, "read-only inputs")
}

View File

@ -202,6 +202,9 @@ func (s *sessionService) KnowledgeQA(
// Start knowledge QA event processing (set session tenant so pipeline session/message lookups use session owner)
ctx = context.WithValue(ctx, types.SessionTenantIDContextKey, req.Session.TenantID)
// Propagate the session ID so stateful sandbox backends (CubeSandbox) can
// bind script execution to a per-session MicroVM instance.
ctx = types.WithSessionID(ctx, req.Session.ID)
logger.Info(ctx, "Triggering question answering event")
setupSpan.Finish(map[string]interface{}{
"stages": len(pipeline),

View File

@ -0,0 +1,144 @@
package service
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// stubSandboxResolver stands in for the per-config resolver. Its presence is
// what makes the collector take the resolving branch at all.
type stubSandboxResolver struct {
mgr sandbox.Manager
err error
}
func (s stubSandboxResolver) Resolve(context.Context, uint64, string) (sandbox.Manager, error) {
return s.mgr, s.err
}
// artifactFallbackManager is a minimal sandbox.Manager that delegates artifact
// reads to a SandboxArtifactSource — used when tests exercise sentinel pins.
type artifactFallbackManager struct {
source SandboxArtifactSource
}
func (m *artifactFallbackManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
panic("unexpected Execute")
}
func (m *artifactFallbackManager) Cleanup(context.Context) error { return nil }
func (m *artifactFallbackManager) GetSandbox() sandbox.Sandbox { return nil }
func (m *artifactFallbackManager) GetType() sandbox.SandboxType {
return sandbox.SandboxTypeCube
}
func (m *artifactFallbackManager) ListSessionFiles(ctx context.Context, sessionID, dir string) ([]sandbox.RemoteDirEntry, error) {
return m.source.ListSessionFiles(ctx, sessionID, dir)
}
func (m *artifactFallbackManager) ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error) {
return m.source.ReadSessionFile(ctx, sessionID, path)
}
// Execution decides the config; every later operation must follow the pin, so
// that re-pointing the agent mid-conversation cannot split a session across
// two backends.
func TestSandboxConfigForExecutionPinsAgentChoice(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
got, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")
require.NoError(t, err)
require.Equal(t, "cfg-a", got)
// Admin re-points the agent at cfg-b: the live sandbox stays on cfg-a.
got, err = sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-b")
require.NoError(t, err)
require.Equal(t, "cfg-a", got)
}
func TestSandboxConfigForExistingSandboxReturnsEmptyWhenUnpinned(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
got, err := sandboxConfigForExistingSandbox(context.Background(), pinner, "s-1")
require.NoError(t, err)
require.Empty(t, got, "no pin means no live sandbox; callers must skip")
}
func TestSandboxConfigForExecutionUsesSentinelForGlobalDefault(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
got, err := sandboxConfigForExecution(context.Background(), pinner, "s-1", "")
require.NoError(t, err)
require.Equal(t, types.SandboxConfigIDGlobalDefault, got)
}
// Attachment staging can be the call that creates the session's first sandbox
// (WriteSessionInputFile provisions on first write), so it must pin like
// execution does - not follow a pin that does not exist yet.
func TestSandboxConfigForExecutionPinsOnFirstStaging(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
staged, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")
require.NoError(t, err)
require.Equal(t, "cfg-a", staged)
// The execution that follows in the same turn must land on the same config.
executed, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")
require.NoError(t, err)
require.Equal(t, staged, executed)
}
// Most deployments run every session on the WEKNORA_SANDBOX_* default, whose
// pin is the sentinel and whose manager is the injected process-wide one. That
// must keep collecting artifacts: resolving the sentinel yields no per-config
// manager, which is not the same as "this session has no sandbox".
func TestArtifactSessionSourceKeepsDefaultBackendForSentinelPin(t *testing.T) {
t.Setenv("WEKNORA_SANDBOX_MODE", "cube")
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
_, err := pinner.Pin(ctx, "s-1", types.SandboxConfigIDGlobalDefault)
require.NoError(t, err)
source := &fakeSandboxSource{}
collector := &ArtifactCollector{
source: source,
resolver: stubSandboxResolver{},
pinner: pinner,
fallbackMgr: &artifactFallbackManager{source: source},
}
got := collector.sessionSource(ctx, "s-1")
require.NotNil(t, got)
// Sentinel pins resolve to the deployment-wide manager, which may be a
// distinct object from c.source even though both read the same backend.
_, ok := got.(SandboxArtifactSource)
require.True(t, ok)
}
// Attachment staging is reached through a runtime type assertion in
// session_agent_qa.go, so a signature drift there does not fail the build - it
// makes every agent turn error out with "does not support session attachment
// staging". This pins the shape that call site asserts.
func TestAgentServiceSatisfiesStagingAssertion(t *testing.T) {
var svc any = &agentService{}
_, ok := svc.(sessionAttachmentStager)
require.True(t, ok)
}
// An unpinned session has no live sandbox, so there is nothing to read even
// though a process-wide source exists.
func TestArtifactSessionSourceSkipsUnpinnedSession(t *testing.T) {
collector := &ArtifactCollector{
source: &fakeSandboxSource{},
resolver: stubSandboxResolver{},
pinner: NewSessionSandboxPinner(newPinTestDB(t)),
}
require.Nil(t, collector.sessionSource(context.Background(), "s-1"))
}

View File

@ -0,0 +1,62 @@
package service
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// A workspace can point an agent at a named Cube/E2B config while the
// deployment default stays docker/local. In that combination the agent still
// registers shell/skill tools against the remote sandbox (initializeSkillsManager
// resolves the same per-config manager), so gating attachment staging on the
// process-wide manager would leave those tools running against an empty
// /workspace/input.
func TestSessionSandboxInputStoreUsesNamedConfigNotDeploymentDefault(t *testing.T) {
t.Setenv("WEKNORA_SANDBOX_MODE", "local")
// The deployment default advertises no session filesystem, standing in for
// docker/local/disabled.
deploymentDefault := &stagingSandboxManager{
sandboxType: sandbox.SandboxTypeLocal,
disableFiles: true,
}
// The workspace's named config does advertise one.
named := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeCube}
svc := &agentService{
sandboxMgr: deploymentDefault,
sandboxResolver: stubSandboxResolver{mgr: named},
sandboxPinner: NewSessionSandboxPinner(newPinTestDB(t)),
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
store, err := svc.sessionSandboxInputStore(ctx, "s-1", "cfg-remote")
require.NoError(t, err)
require.NotNil(t, store, "named remote config must still stage attachments")
}
// The mirror case: no named config means the deployment default decides, and a
// backend without a session filesystem must not stage anything.
func TestSessionSandboxInputStoreSkipsWhenDeploymentDefaultHasNoFilesystem(t *testing.T) {
t.Setenv("WEKNORA_SANDBOX_MODE", "local")
deploymentDefault := &stagingSandboxManager{
sandboxType: sandbox.SandboxTypeLocal,
disableFiles: true,
}
svc := &agentService{
sandboxMgr: deploymentDefault,
sandboxResolver: stubSandboxResolver{},
sandboxPinner: NewSessionSandboxPinner(newPinTestDB(t)),
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
store, err := svc.sessionSandboxInputStore(ctx, "s-1", "")
require.NoError(t, err)
require.Nil(t, store)
}

View File

@ -0,0 +1,178 @@
// Package service: session -> sandbox config pin.
//
// A session's remote sandbox is long-lived (created with onTimeout=pause, so
// its TTL pauses rather than destroys it), while the operations around it -
// skill execution, attachment upload, artifact collection, teardown - each
// resolve a backend independently at different points in time.
//
// If those points read "whichever config the agent points at right now", an
// admin re-pointing an agent mid-conversation would make artifact collection
// query the wrong account (artifacts silently vanish) and teardown fail
// (a paused sandbox nobody knows the ID of, billing forever).
//
// The pin records which config the session's CURRENT sandbox lives on. It is
// deliberately ephemeral: sessions outlive sandboxes by months, so a permanent
// pin would make "nothing references this config" never become true.
package service
import (
"context"
"database/sql"
"fmt"
"strings"
"gorm.io/gorm"
"github.com/Tencent/WeKnora/internal/types"
)
// SessionSandboxPinner is the only place session sandbox pins are read or
// written. Centralising it is what keeps the four entry points consistent.
type SessionSandboxPinner struct {
db *gorm.DB
}
// NewSessionSandboxPinner returns a pinner over the sessions table.
func NewSessionSandboxPinner(db *gorm.DB) *SessionSandboxPinner {
return &SessionSandboxPinner{db: db}
}
// Read returns the pinned config ID, or "" when the session has no live
// sandbox. Note the pin is an optimistic hint: the sandbox may have been
// reclaimed out of band (see Clear).
func (p *SessionSandboxPinner) Read(ctx context.Context, sessionID string) (string, error) {
pinned, _, err := p.read(ctx, sessionID)
return pinned, err
}
// read additionally reports whether the session row exists at all, which Pin
// needs and Read deliberately hides: a caller asking "does this session have a
// live sandbox" gets the same "no" either way, but a caller that just created
// a sandbox must not mistake a vanished session for a clean pin.
//
// Soft-deleted sessions count as absent — GORM scopes them out — which is what
// we want, since deleting a session also destroys its sandbox.
func (p *SessionSandboxPinner) read(ctx context.Context, sessionID string) (string, bool, error) {
var pinned sql.NullString
result := p.db.WithContext(ctx).
Model(&types.Session{}).
Where("id = ?", sessionID).
Select("sandbox_config_id").
Scan(&pinned)
if result.Error != nil {
return "", false, result.Error
}
if result.RowsAffected == 0 {
return "", false, nil
}
if !pinned.Valid {
return "", true, nil
}
return pinned.String, true, nil
}
// Pin claims the session for configID and returns the winning value.
//
// The conditional update is what makes concurrent first-sandbox creations
// safe: losers adopt the winner's config instead of building a second sandbox
// on a second backend.
//
// A missing or soft-deleted session is an error rather than an empty result.
// Pin is called just after a sandbox was created, so answering "" — which
// means "no live sandbox" everywhere else — would hide a real sandbox whose
// backend nobody recorded, leaving the orphan reaper as the only way back.
func (p *SessionSandboxPinner) Pin(
ctx context.Context, sessionID, configID string,
) (string, error) {
configID = strings.TrimSpace(configID)
if configID == "" {
configID = types.SandboxConfigIDGlobalDefault
}
// Two attempts: a concurrent Clear can hand the row back unpinned between
// our update and our read, and returning that empty value would be the
// same silent lie as a missing session.
for attempt := 0; attempt < 2; attempt++ {
result := p.db.WithContext(ctx).
Model(&types.Session{}).
Where("id = ? AND (sandbox_config_id IS NULL OR sandbox_config_id = ?)",
sessionID, "").
Update("sandbox_config_id", configID)
if result.Error != nil {
return "", result.Error
}
if result.RowsAffected > 0 {
return configID, nil
}
pinned, found, err := p.read(ctx, sessionID)
if err != nil {
return "", err
}
if !found {
return "", fmt.Errorf(
"sandbox: pin session %s to config %s: %w",
sessionID, configID, gorm.ErrRecordNotFound)
}
if pinned != "" {
// Someone else pinned first; adopt their choice.
return pinned, nil
}
}
return "", fmt.Errorf(
"sandbox: pin session %s to config %s: lost the claim race twice",
sessionID, configID)
}
// Clear releases the pin once the sandbox is gone, so the session's next
// sandbox follows its agent's current backend choice.
//
// Best effort by nature: when the reaper reclaims an orphan from the provider
// side the binding is already gone, so there is nothing to map back to a
// session and the pin is left stale. Readers must therefore treat a non-empty
// pin as a hint, not a guarantee that the sandbox still exists.
func (p *SessionSandboxPinner) Clear(ctx context.Context, sessionID string) error {
return p.db.WithContext(ctx).
Model(&types.Session{}).
Where("id = ?", sessionID).
Update("sandbox_config_id", nil).Error
}
// sandboxConfigForExecution decides which config a session's sandbox runs on.
//
// Skill execution and attachment staging can be the first operation that creates
// a session sandbox, so they adopt an existing pin and otherwise claim the
// agent's current choice. Later operations must follow the pin instead.
func sandboxConfigForExecution(
ctx context.Context,
pinner *SessionSandboxPinner,
sessionID string,
agentConfigID string,
) (string, error) {
if pinner == nil || strings.TrimSpace(sessionID) == "" {
return agentConfigID, nil
}
pinned, err := pinner.Read(ctx, sessionID)
if err != nil {
return "", err
}
if pinned != "" {
return pinned, nil
}
return pinner.Pin(ctx, sessionID, agentConfigID)
}
// sandboxConfigForExistingSandbox returns the config an already-created
// sandbox lives on, or "" when the session has none.
//
// Artifact collection and teardown deliberately never consult the agent: the
// agent's current choice may no longer describe the long-lived sandbox they are
// acting on.
func sandboxConfigForExistingSandbox(
ctx context.Context,
pinner *SessionSandboxPinner,
sessionID string,
) (string, error) {
if pinner == nil || strings.TrimSpace(sessionID) == "" {
return "", nil
}
return pinner.Read(ctx, sessionID)
}

View File

@ -0,0 +1,136 @@
package service
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/Tencent/WeKnora/internal/types"
)
func newPinTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.Migrator().DropTable(&types.Session{}))
require.NoError(t, db.AutoMigrate(&types.Session{}))
require.NoError(t, db.Model(&types.Session{}).Create(map[string]any{
"id": "s-1",
"tenant_id": uint64(7),
}).Error)
return db
}
func TestPinWritesWhenUnset(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
got, err := pinner.Pin(ctx, "s-1", "cfg-a")
require.NoError(t, err)
require.Equal(t, "cfg-a", got)
read, err := pinner.Read(ctx, "s-1")
require.NoError(t, err)
require.Equal(t, "cfg-a", read)
}
// Two concurrent first-sandbox creations must converge on one config, or the
// session would end up with two sandboxes on two backends.
func TestPinIsIdempotentAndReturnsExistingWinner(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
first, err := pinner.Pin(ctx, "s-1", "cfg-a")
require.NoError(t, err)
require.Equal(t, "cfg-a", first)
second, err := pinner.Pin(ctx, "s-1", "cfg-b")
require.NoError(t, err)
require.Equal(t, "cfg-a", second, "the first writer wins; later callers adopt it")
}
func TestPinNormalizesEmptyConfigToSentinel(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
got, err := pinner.Pin(ctx, "s-1", "")
require.NoError(t, err)
require.Equal(t, types.SandboxConfigIDGlobalDefault, got)
}
// A padded ID must land in the column exactly as Read will compare it, or the
// conditional claim would never recognise its own write.
func TestPinTrimsConfigIDBeforeStoring(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
got, err := pinner.Pin(ctx, "s-1", " cfg-a ")
require.NoError(t, err)
require.Equal(t, "cfg-a", got)
read, err := pinner.Read(ctx, "s-1")
require.NoError(t, err)
require.Equal(t, "cfg-a", read)
}
// Pin runs right after a sandbox was created, so a vanished session must be an
// error: "" would read as "no live sandbox" and abandon a real one.
func TestPinFailsWhenSessionIsGone(t *testing.T) {
db := newPinTestDB(t)
pinner := NewSessionSandboxPinner(db)
ctx := context.Background()
_, err := pinner.Pin(ctx, "missing", "cfg-a")
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
require.NoError(t, db.Delete(&types.Session{}, "id = ?", "s-1").Error)
_, err = pinner.Pin(ctx, "s-1", "cfg-a")
require.ErrorIs(t, err, gorm.ErrRecordNotFound,
"a soft-deleted session already had its sandbox destroyed")
}
// Read keeps the lenient contract: absent session and unpinned session are
// both simply "no live sandbox".
func TestReadReportsNoSandboxForMissingSession(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
read, err := pinner.Read(context.Background(), "missing")
require.NoError(t, err)
require.Empty(t, read)
}
// The pin dies with the sandbox: after teardown the session must be free to
// follow its agent's CURRENT backend choice.
func TestClearReleasesPin(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
_, err := pinner.Pin(ctx, "s-1", "cfg-a")
require.NoError(t, err)
require.NoError(t, pinner.Clear(ctx, "s-1"))
read, err := pinner.Read(ctx, "s-1")
require.NoError(t, err)
require.Empty(t, read)
}
// Session delete soft-deletes the row before any follow-up work. Destroy must
// therefore read sandbox_config_id first; otherwise the pinner sees an absent
// session and teardown resolves the wrong backend (T4 regression).
func TestSoftDeleteHidesSandboxPin(t *testing.T) {
db := newPinTestDB(t)
pinner := NewSessionSandboxPinner(db)
ctx := context.Background()
_, err := pinner.Pin(ctx, "s-1", "cfg-a")
require.NoError(t, err)
require.NoError(t, db.Delete(&types.Session{}, "id = ?", "s-1").Error)
read, err := pinner.Read(ctx, "s-1")
require.NoError(t, err)
require.Empty(t, read, "soft-deleted session must not expose its pin")
}

View File

@ -0,0 +1,625 @@
// Package service: sandbox backend config management.
//
// The load-bearing rule: some fields decide whether a config can still OPERATE
// the sandboxes it already created. Overwriting them in place while sandboxes
// are alive breaks those sandboxes in one of two ways, and both are bad enough
// to refuse the save.
//
// Losing the control plane (provider, API URL, API key) means the new
// credentials have no authority over the old sandboxes, so they can no longer be
// listed or deleted. Session sandboxes are created with onTimeout=pause, so the
// provider TTL never reclaims them either - the leak is permanent and it bills.
// A paused sandbox is also what a session expects to RESUME, so conversations
// break on top.
//
// Losing the data plane (E2B sandbox domain; Cube proxy URL and sandbox domain)
// keeps cleanup possible, but every envd request now goes to the wrong host.
// Every live session on this config fails at once - skill execution, attachment
// staging, artifact collection - while the sandboxes stay alive and keep billing
// until their sessions are deleted.
//
// Hence both groups are refused while sandboxes exist. The admin ends the owning
// sessions or creates a second config and re-points agents; both keep the old
// values intact, which is what keeps cleanup possible.
package service
import (
"context"
stderrors "errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/Tencent/WeKnora/internal/application/repository"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
const sandboxConfigCleanupTimeout = 20 * time.Second
// SandboxIdentityChanged reports whether sandboxes already created under oldCfg
// would stop being operable under newCfg. Names, templates, TTLs, HTTP timeouts
// and env vars deliberately do not count: they only shape FUTURE sandboxes.
//
// newCfg must already have been merged with the stored config (see
// types.MergeSandboxConfigForUpdate). The API masks secrets on read, so
// comparing a raw payload would report a key rotation on every single save and
// leave the config permanently uneditable.
//
// The comparison needs no deployment baseline: named configs inherit nothing, so
// the stored fields are the whole identity. It is also deliberately free of
// validation — see sandbox.IdentityOf for why an unreachable old endpoint must
// still be judgeable.
func SandboxIdentityChanged(oldCfg, newCfg *types.TenantSandboxConfig) bool {
if oldCfg == nil {
// Nothing exists yet, so nothing can be stranded.
return false
}
if newCfg == nil {
return true
}
return sandbox.IdentityOf(oldCfg) != sandbox.IdentityOf(newCfg)
}
// ErrSandboxesStillLive is returned when an identity change or deletion is
// refused because the current credentials still own provider resources.
var ErrSandboxesStillLive = stderrors.New("sandbox config still owns live sandboxes")
// SandboxesStillLiveError carries the provider inventory the handler must show
// in its 409 response; recomputing it could race and disagree with the refusal.
type SandboxesStillLiveError struct {
Inventory SandboxInventory
}
func (e *SandboxesStillLiveError) Error() string {
return fmt.Sprintf("%s: %d", ErrSandboxesStillLive, e.Inventory.SandboxCount)
}
func (e *SandboxesStillLiveError) Unwrap() error {
return ErrSandboxesStillLive
}
// ErrSandboxInventoryUnverifiable is returned when the provider cannot be
// reached to answer "does this config still own sandboxes?".
//
// It is deliberately distinct from ErrSandboxesStillLive: one means "there ARE
// sandboxes, deal with them", the other means "we cannot tell". The second is
// the only case a force delete may override, because an endpoint whose DNS
// record is gone would otherwise make its config permanently undeletable.
var ErrSandboxInventoryUnverifiable = stderrors.New(
"cannot verify whether the sandbox config still owns sandboxes")
// ErrSandboxConfigNameRequired is a sentinel so transports can classify this as
// bad input without matching on the message text.
var ErrSandboxConfigNameRequired = stderrors.New("sandbox config name is required")
// ErrNamedSandboxBackendUnsupported marks a sandbox type that cannot be stored
// as a user-facing named backend config.
var ErrNamedSandboxBackendUnsupported = stderrors.New(
"named sandbox configs only support cube and e2b backends",
)
// SandboxInventory describes what a config holds and who a change disturbs.
type SandboxInventory struct {
SandboxCount int `json:"sandbox_count"`
SessionIDs []string `json:"session_ids,omitempty"`
AgentNames []string `json:"agent_names,omitempty"`
// Unverifiable reports that SandboxCount is unknown rather than zero
// because the provider could not be reached. The management page must say
// so instead of rendering a reassuring "0 sandboxes".
Unverifiable bool `json:"unverifiable,omitempty"`
}
// CreateSandboxConfigInput is the create payload.
type CreateSandboxConfigInput struct {
Name string
Description string
Config *types.TenantSandboxConfig
}
// UpdateSandboxConfigInput is the update payload. Config may carry redacted
// placeholders that resolve against the stored row.
type UpdateSandboxConfigInput struct {
Name string
Description string
Config *types.TenantSandboxConfig
}
// SandboxConfigAgentRepo is the slice of the agent repository this service
// needs. Agent references are warnings, never grounds for refusing a change.
type SandboxConfigAgentRepo interface {
ListNamesBySandboxConfigID(ctx context.Context, tenantID uint64, configID string) ([]string, error)
}
// TenantSandboxConfigService owns the sandbox config lifecycle.
type TenantSandboxConfigService struct {
repo repository.TenantSandboxConfigRepository
agents SandboxConfigAgentRepo
globalCfg *sandbox.Config
now func() time.Time
// newClient is injectable so tests can supply a provider inventory.
newClient func(*sandbox.Config) (sandbox.ConfigSandboxClient, error)
}
// NewTenantSandboxConfigService wires the config service.
func NewTenantSandboxConfigService(
repo repository.TenantSandboxConfigRepository,
agents SandboxConfigAgentRepo,
globalCfg *sandbox.Config,
) *TenantSandboxConfigService {
return &TenantSandboxConfigService{
repo: repo,
agents: agents,
globalCfg: globalCfg,
now: time.Now,
newClient: func(cfg *sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return sandbox.NewRemoteClientForCheck(cfg)
},
}
}
// SanitizeSandboxConfig resolves redacted secrets and validates the payload
// before it can be persisted.
func SanitizeSandboxConfig(
incoming, existing *types.TenantSandboxConfig,
) (*types.TenantSandboxConfig, error) {
if incoming == nil {
return nil, nil
}
merged := types.MergeSandboxConfigForUpdate(incoming, existing)
if merged.SandboxType != "" {
if _, err := sandbox.ParseSandboxType(merged.SandboxType); err != nil {
return nil, err
}
}
for _, endpoint := range sandboxConfigEndpoints(merged) {
if err := sandbox.ValidateOutboundURL(endpoint); err != nil {
return nil, err
}
}
// Without an AES key the Value() hook would persist these secrets in
// plaintext. Refuse instead of silently downgrading storage security.
if sandboxConfigHasSecrets(merged) && utils.GetAESKey() == nil {
return nil, apperrors.NewBadRequestError(
"SYSTEM_AES_KEY is not configured; refusing to store sandbox credentials in plaintext",
)
}
// Reject an incomplete config here rather than at first sandbox allocation.
// Resolving is what the runtime does, so both paths agree by construction.
// The baseline passed in is irrelevant to the outcome: named configs inherit
// no provider field, so only merged decides what is missing.
// Returned unwrapped so respondSandboxConfigServiceError can classify the
// sentinel; wrapping it in an AppError here would hide the chain.
if _, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DefaultConfig()); err != nil {
return nil, err
}
return merged, nil
}
func validateNamedSandboxBackend(cfg *types.TenantSandboxConfig) error {
if cfg == nil || strings.TrimSpace(cfg.SandboxType) == "" {
return apperrors.NewBadRequestError("sandbox backend type is required")
}
if !sandbox.IsNamedSandboxBackendType(cfg.SandboxType) {
return fmt.Errorf("%w", ErrNamedSandboxBackendUnsupported)
}
return nil
}
func filterPublicSandboxConfigs(
list []*types.TenantSandboxConfigEntity,
) []*types.TenantSandboxConfigEntity {
if len(list) == 0 {
return list
}
out := make([]*types.TenantSandboxConfigEntity, 0, len(list))
for _, e := range list {
if types.IsSandboxWorkspacePolicyRow(e) {
continue
}
out = append(out, e)
}
return out
}
func findWorkspacePolicyRow(
list []*types.TenantSandboxConfigEntity,
) *types.TenantSandboxConfigEntity {
for _, e := range list {
if types.IsSandboxWorkspacePolicyRow(e) {
return e
}
}
return nil
}
// WorkspaceScriptsDisabled reports whether agents that rely on the deployment
// default (empty sandbox_config_id) must not execute skill scripts.
func (s *TenantSandboxConfigService) WorkspaceScriptsDisabled(
ctx context.Context, tenantID uint64,
) (bool, error) {
list, err := s.repo.ListByTenant(ctx, tenantID)
if err != nil {
return false, err
}
return findWorkspacePolicyRow(list) != nil, nil
}
// SetWorkspaceScriptsDisabled toggles workspace-level script execution for
// agents that do not point at a named cube/e2b config.
func (s *TenantSandboxConfigService) SetWorkspaceScriptsDisabled(
ctx context.Context, tenantID uint64, disabled bool,
) error {
list, err := s.repo.ListByTenant(ctx, tenantID)
if err != nil {
return err
}
existing := findWorkspacePolicyRow(list)
if disabled {
if existing != nil {
return nil
}
entity := &types.TenantSandboxConfigEntity{
ID: uuid.New().String(),
TenantID: tenantID,
Name: types.SandboxWorkspacePolicyConfigName,
Description: "",
SandboxType: string(sandbox.SandboxTypeDisabled),
Config: &types.TenantSandboxConfig{SandboxType: string(sandbox.SandboxTypeDisabled)},
}
return s.repo.Create(ctx, entity)
}
if existing == nil {
return nil
}
return s.repo.SoftDelete(ctx, tenantID, existing.ID)
}
// Create stores a new config.
func (s *TenantSandboxConfigService) Create(
ctx context.Context, tenantID uint64, in CreateSandboxConfigInput,
) (*types.TenantSandboxConfigEntity, error) {
merged, err := SanitizeSandboxConfig(in.Config, nil)
if err != nil {
return nil, err
}
if err := validateNamedSandboxBackend(merged); err != nil {
return nil, err
}
name := strings.TrimSpace(in.Name)
if name == "" {
return nil, ErrSandboxConfigNameRequired
}
entity := &types.TenantSandboxConfigEntity{
ID: uuid.New().String(),
TenantID: tenantID,
Name: name,
Description: in.Description,
Config: merged,
}
if merged != nil {
entity.SandboxType = merged.SandboxType
}
if err := s.repo.Create(ctx, entity); err != nil {
return nil, err
}
return entity, nil
}
// List returns the workspace's user-facing configs (policy row excluded).
func (s *TenantSandboxConfigService) List(
ctx context.Context, tenantID uint64,
) ([]*types.TenantSandboxConfigEntity, error) {
list, err := s.repo.ListByTenant(ctx, tenantID)
if err != nil {
return nil, err
}
return filterPublicSandboxConfigs(list), nil
}
// Get returns one config, or nil when absent.
func (s *TenantSandboxConfigService) Get(
ctx context.Context, tenantID uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
entity, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil || entity == nil {
return nil, err
}
if types.IsSandboxWorkspacePolicyRow(entity) {
return nil, nil
}
return entity, nil
}
// Inventory answers what changing or deleting this config would disturb.
//
// An unreachable provider is reported through Unverifiable rather than as an
// error: the management page still has to render the card, and the agent names
// it warns about come from our own database.
func (s *TenantSandboxConfigService) Inventory(
ctx context.Context, tenantID uint64, id string,
) (SandboxInventory, error) {
entity, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil {
return SandboxInventory{}, err
}
if entity == nil {
return SandboxInventory{}, apperrors.NewNotFoundError("sandbox config not found")
}
summaries, err := s.listSandboxes(ctx, entity.Config, tenantID, id)
inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
if err != nil {
logger.Warnf(ctx, "[sandbox] inventory of config %s is unverifiable: %v", id, err)
inv.Unverifiable = true
}
return inv, nil
}
// listSandboxes enumerates what the config currently owns. A nil client means
// the backend holds no remote resources at all, which is a verified empty.
func (s *TenantSandboxConfigService) listSandboxes(
ctx context.Context,
cfg *types.TenantSandboxConfig,
tenantID uint64,
id string,
) ([]sandbox.RemoteSandboxSummary, error) {
client, err := s.clientFor(cfg)
if err != nil {
return nil, err
}
if client == nil {
return nil, nil
}
return sandbox.ListConfigSandboxes(ctx, client, tenantID, id)
}
// Update applies an edit. Identity edits are cordoned before inventory and
// swept afterwards using the old client so credentials are never overwritten
// while they still own provider resources.
func (s *TenantSandboxConfigService) Update(
ctx context.Context, tenantID uint64, id string, in UpdateSandboxConfigInput,
) (*types.TenantSandboxConfigEntity, error) {
entity, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil || entity == nil {
return nil, err
}
if types.IsSandboxWorkspacePolicyRow(entity) {
return nil, apperrors.NewBadRequestError("workspace policy cannot be edited here")
}
merged, err := SanitizeSandboxConfig(in.Config, entity.Config)
if err != nil {
return nil, err
}
if err := validateNamedSandboxBackend(merged); err != nil {
return nil, err
}
if !SandboxIdentityChanged(entity.Config, merged) {
return s.writeConfig(ctx, entity, in, merged)
}
if err := s.repo.SetCordon(ctx, tenantID, id, s.now()); err != nil {
return nil, err
}
defer s.clearCordonAfterRequest(ctx, tenantID, id)
// When old credentials no longer reach the provider we cannot enumerate
// sandboxes to refuse the edit — but blocking the save traps the admin on
// a key they are trying to fix. Proceed and skip the post-write sweep;
// sandboxes we cannot see may become orphans and need provider-side cleanup.
oldClient, err := s.clientFor(entity.Config)
if err != nil {
logger.Warnf(ctx,
"[sandbox] config %s: old credentials unusable for inventory: %v; proceeding",
id, err)
oldClient = nil
}
if oldClient != nil {
summaries, listErr := sandbox.ListConfigSandboxes(ctx, oldClient, tenantID, id)
if listErr != nil {
logger.Warnf(ctx,
"[sandbox] config %s: cannot verify sandbox inventory with old credentials: %v; proceeding",
id, listErr)
oldClient = nil
} else if len(summaries) > 0 {
inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
return nil, &SandboxesStillLiveError{Inventory: inv}
}
}
updated, err := s.writeConfig(ctx, entity, in, merged)
if err != nil {
return nil, err
}
if oldClient != nil {
s.sweepAfterWrite(ctx, oldClient, tenantID, id)
}
return updated, nil
}
// Delete refuses only while the config still owns sandboxes. Agent references
// are permanent state and are surfaced as warnings by callers, not blockers.
//
// force covers exactly one case: the provider could not be reached, so we cannot
// tell whether anything is live. Without it a config whose endpoint's DNS record
// disappeared could never be removed — unlike an edit, deletion has no "create a
// second config" way out. It does NOT override sandboxes we can actually see;
// those still have to be dealt with through their sessions, otherwise the forced
// deletion would be precisely the permanent leak this whole flow prevents.
func (s *TenantSandboxConfigService) Delete(
ctx context.Context, tenantID uint64, id string, force bool,
) error {
entity, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil {
return err
}
// Reporting success for a config that is not there would let the UI drop a
// card the workspace still has, so absence is an explicit 404.
if entity == nil {
return apperrors.NewNotFoundError("sandbox config not found")
}
if types.IsSandboxWorkspacePolicyRow(entity) {
return apperrors.NewBadRequestError("workspace policy cannot be deleted here")
}
summaries, listErr := s.listSandboxes(ctx, entity.Config, tenantID, id)
if listErr != nil {
if !force {
return fmt.Errorf("%w: %v", ErrSandboxInventoryUnverifiable, listErr)
}
logger.Warnf(ctx,
"[sandbox] force-deleting config %s without verifying its sandboxes: %v",
id, listErr)
}
if len(summaries) > 0 {
inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
return &SandboxesStillLiveError{Inventory: inv}
}
return s.repo.SoftDelete(ctx, tenantID, id)
}
func (s *TenantSandboxConfigService) clientFor(
cfg *types.TenantSandboxConfig,
) (sandbox.ConfigSandboxClient, error) {
// The baseline only supplies the deployment's execution timeout; every
// provider field comes from cfg, so a nil globalCfg cannot change which
// backend this client talks to.
base := s.globalCfg
if base == nil {
base = sandbox.DefaultConfig()
}
effective, err := sandbox.ResolveEffectiveConfig(cfg, base)
if err != nil {
return nil, err
}
switch effective.Type {
case sandbox.SandboxTypeCube, sandbox.SandboxTypeE2B:
return s.newClient(effective)
default:
return nil, nil
}
}
func (s *TenantSandboxConfigService) writeConfig(
ctx context.Context,
entity *types.TenantSandboxConfigEntity,
in UpdateSandboxConfigInput,
merged *types.TenantSandboxConfig,
) (*types.TenantSandboxConfigEntity, error) {
if name := strings.TrimSpace(in.Name); name != "" {
entity.Name = name
}
entity.Description = in.Description
entity.Config = merged
if merged != nil {
entity.SandboxType = merged.SandboxType
}
if err := s.repo.Update(ctx, entity); err != nil {
return nil, err
}
return entity, nil
}
func (s *TenantSandboxConfigService) inventoryFromSummaries(
ctx context.Context,
tenantID uint64,
id string,
summaries []sandbox.RemoteSandboxSummary,
) SandboxInventory {
inv := SandboxInventory{SandboxCount: len(summaries)}
for _, summary := range summaries {
if sessionID := summary.Metadata[sandbox.MetadataSessionIDKey()]; sessionID != "" {
inv.SessionIDs = append(inv.SessionIDs, sessionID)
}
}
if s.agents == nil {
return inv
}
names, err := s.agents.ListNamesBySandboxConfigID(ctx, tenantID, id)
if err != nil {
logger.Warnf(ctx, "[sandbox] list agents for config %s: %v", id, err)
return inv
}
inv.AgentNames = names
return inv
}
func (s *TenantSandboxConfigService) clearCordonAfterRequest(
ctx context.Context,
tenantID uint64,
id string,
) {
cleanupCtx, cancel := context.WithTimeout(
context.WithoutCancel(ctx), sandboxConfigCleanupTimeout)
defer cancel()
if err := s.repo.ClearCordon(cleanupCtx, tenantID, id); err != nil {
logger.Warnf(ctx, "[sandbox] clear cordon on config %s: %v", id, err)
}
}
func (s *TenantSandboxConfigService) sweepAfterWrite(
ctx context.Context,
oldClient sandbox.ConfigSandboxClient,
tenantID uint64,
id string,
) {
cleanupCtx, cancel := context.WithTimeout(
context.WithoutCancel(ctx), sandboxConfigCleanupTimeout)
defer cancel()
deleted, err := sandbox.ReleaseConfigSandboxes(cleanupCtx, oldClient, tenantID, id)
if err != nil {
logger.Warnf(ctx, "[sandbox] post-write sweep of config %s failed: %v", id, err)
return
}
if deleted > 0 {
logger.Infof(ctx,
"[sandbox] swept %d sandbox(es) created during the cordon window on config %s",
deleted, id)
}
}
// sandboxConfigEndpoints returns every non-empty tenant-supplied URL.
func sandboxConfigEndpoints(cfg *types.TenantSandboxConfig) []string {
if cfg == nil {
return nil
}
var endpoints []string
if cfg.Cube != nil {
for _, raw := range []string{cfg.Cube.APIURL, cfg.Cube.ProxyURL} {
if raw != "" {
endpoints = append(endpoints, raw)
}
}
}
if cfg.E2B != nil && cfg.E2B.APIURL != "" {
endpoints = append(endpoints, cfg.E2B.APIURL)
}
return endpoints
}
// sandboxConfigHasSecrets reports whether cfg carries any value that must be
// encrypted at rest.
func sandboxConfigHasSecrets(cfg *types.TenantSandboxConfig) bool {
if cfg == nil {
return false
}
if cfg.Cube != nil && cfg.Cube.APIKey != "" {
return true
}
if cfg.E2B != nil && cfg.E2B.APIKey != "" {
return true
}
for _, value := range cfg.EnvVars {
if value != "" {
return true
}
}
return false
}

View File

@ -0,0 +1,757 @@
package service
import (
"context"
stderrors "errors"
"net/http"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// testGlobalSandboxConfig mirrors a deployment's WEKNORA_SANDBOX_* values. Named
// configs inherit none of the provider fields from it; it is here so the service
// under test is wired the way production wires it.
func testGlobalSandboxConfig() *sandbox.Config {
cfg := sandbox.DefaultConfig()
cfg.Type = sandbox.SandboxTypeE2B
cfg.E2BAPIURL = "https://api.e2b.app"
cfg.E2BSandboxDomain = "e2b.app"
cfg.E2BAPIKey = "global-key"
cfg.E2BTemplate = "global-template"
return cfg
}
func e2bCfg(key, url, domain, template string, ttl int) *types.TenantSandboxConfig {
return &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIKey: key, APIURL: url, SandboxDomain: domain, TemplateID: template,
E2BSandboxTTLSeconds: ttl,
},
}
}
func cubeCfg(key, apiURL, proxyURL, domain string) *types.TenantSandboxConfig {
return &types.TenantSandboxConfig{
SandboxType: "cube",
Cube: &types.CubeSandboxConfig{
APIKey: key, APIURL: apiURL, ProxyURL: proxyURL, SandboxDomain: domain,
},
}
}
func TestSandboxIdentityChanged(t *testing.T) {
tests := []struct {
name string
old, new *types.TenantSandboxConfig
want bool
}{
// Control plane: losing these loses the ability to clean up, and the
// leak bills forever.
{
name: "api key rotation changes identity",
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
new: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
want: true,
},
{
name: "endpoint change changes identity",
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
new: e2bCfg("key-a", "https://self.hosted", "e2b.app", "t1", 300),
want: true,
},
{
name: "provider switch changes identity",
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
new: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app"),
want: true,
},
// Data plane: the control plane still works so cleanup stays possible,
// but every envd request now goes to the wrong host, so every live
// session on this config fails at once.
{
name: "e2b sandbox domain change strands live sessions",
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
new: e2bCfg("key-a", "https://api.e2b.app", "e2b.dev", "t1", 300),
want: true,
},
{
name: "cube proxy url change strands live sessions",
old: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app"),
new: cubeCfg("key-a", "https://cube.example.com", "https://proxy2.example.com", "cube.app"),
want: true,
},
{
name: "cube sandbox domain change strands live sessions",
old: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app"),
new: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube2.app"),
want: true,
},
// Not identity changes: these only shape FUTURE sandboxes, so refusing
// them would be pure friction.
{
name: "template change only affects future sandboxes",
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t2", 300),
want: false,
},
{
name: "ttl change is not an identity change",
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),
want: false,
},
{
// Nothing is inherited, so filling in an endpoint that was blank
// really does re-point the config at a different account.
name: "filling in a blank endpoint changes identity",
old: &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "key-a"},
},
new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 0),
want: true,
},
{
// Only the ACTIVE provider's fields describe where the sandboxes
// are; a leftover sub-struct from an earlier switch must not count.
name: "inactive provider fields are ignored",
old: &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "key-a"},
Cube: &types.CubeSandboxConfig{APIKey: "stale-a"},
},
new: &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "key-a"},
Cube: &types.CubeSandboxConfig{APIKey: "stale-b"},
},
want: false,
},
{
name: "no previous config means nothing to strand",
old: nil,
new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, SandboxIdentityChanged(tt.old, tt.new))
})
}
}
// The UI never sends the real API key back - it echoes a mask. Comparing the
// incoming payload directly would therefore report an identity change on EVERY
// save and make the config permanently uneditable. This pins the required
// ordering: merge first, judge second.
func TestSandboxIdentityChangedAfterMaskMerge(t *testing.T) {
stored := e2bCfg("real-key", "https://api.e2b.app", "e2b.app", "t1", 300)
incoming := e2bCfg(types.RedactedSecretPlaceholder, "https://api.e2b.app", "e2b.app", "t1", 300)
merged := types.MergeSandboxConfigForUpdate(incoming, stored)
require.False(t,
SandboxIdentityChanged(stored, merged),
"a masked key that merges back to the stored one is not a rotation")
}
// An admin re-points a config precisely because its old endpoint died, so the
// verdict must not depend on that endpoint being reachable or even resolvable.
// Routing this through the SSRF-guarding resolver would lock the config down at
// the worst possible moment.
func TestSandboxIdentityChangedJudgesUnreachableOldEndpoint(t *testing.T) {
dead := cubeCfg("key-a", "https://decommissioned.invalid", "https://proxy.invalid", "cube.app")
live := cubeCfg("key-a", "https://cube.example.com", "https://proxy.invalid", "cube.app")
require.True(t, SandboxIdentityChanged(dead, live))
require.False(t, SandboxIdentityChanged(dead, dead))
}
// fakeConfigRepo records cordon transitions so tests can assert the sequence
// that prevents old credentials from being overwritten while they still own
// provider resources.
type fakeConfigRepo struct {
entity *types.TenantSandboxConfigEntity
policy *types.TenantSandboxConfigEntity
events []string
updated *types.TenantSandboxConfigEntity
deleted bool
onSetCordon func()
onUpdate func()
clearCordonCtxErr error
}
func (f *fakeConfigRepo) Create(_ context.Context, e *types.TenantSandboxConfigEntity) error {
if types.IsSandboxWorkspacePolicyRow(e) {
f.policy = e
return nil
}
f.entity = e
return nil
}
func (f *fakeConfigRepo) GetByID(
_ context.Context, _ uint64, _ string,
) (*types.TenantSandboxConfigEntity, error) {
f.events = append(f.events, "get")
return f.entity, nil
}
func (f *fakeConfigRepo) ListByTenant(
context.Context, uint64,
) ([]*types.TenantSandboxConfigEntity, error) {
var out []*types.TenantSandboxConfigEntity
if f.entity != nil {
out = append(out, f.entity)
}
if f.policy != nil {
out = append(out, f.policy)
}
return out, nil
}
func (f *fakeConfigRepo) Update(
_ context.Context, e *types.TenantSandboxConfigEntity,
) error {
f.events = append(f.events, "write")
f.updated = e
if f.onUpdate != nil {
f.onUpdate()
}
return nil
}
func (f *fakeConfigRepo) SoftDelete(_ context.Context, _ uint64, id string) error {
f.events = append(f.events, "delete")
if f.policy != nil && f.policy.ID == id {
f.policy = nil
}
f.deleted = true
return nil
}
func (f *fakeConfigRepo) SetCordon(_ context.Context, _ uint64, _ string, _ time.Time) error {
f.events = append(f.events, "cordon")
if f.onSetCordon != nil {
f.onSetCordon()
}
return nil
}
func (f *fakeConfigRepo) ClearCordon(ctx context.Context, _ uint64, _ string) error {
f.events = append(f.events, "uncordon")
f.clearCordonCtxErr = ctx.Err()
return nil
}
type stubAgentRepo struct {
names []string
err error
}
func (s stubAgentRepo) ListNamesBySandboxConfigID(
context.Context, uint64, string,
) ([]string, error) {
return s.names, s.err
}
type stubProviderClient struct {
inventories [][]sandbox.RemoteSandboxSummary
listCalls int
deleted []string
deleteCtxErr error
}
func (s *stubProviderClient) List(
ctx context.Context, _ sandbox.RemoteListFilter,
) ([]sandbox.RemoteSandboxSummary, error) {
s.listCalls++
if len(s.inventories) == 0 {
return nil, nil
}
idx := s.listCalls - 1
if idx >= len(s.inventories) {
idx = len(s.inventories) - 1
}
return s.inventories[idx], nil
}
func (s *stubProviderClient) Delete(ctx context.Context, sandboxID string) error {
s.deleted = append(s.deleted, sandboxID)
s.deleteCtxErr = ctx.Err()
return nil
}
func newTestConfigService(
t *testing.T,
repo *fakeConfigRepo,
client *stubProviderClient,
agents stubAgentRepo,
) *TenantSandboxConfigService {
t.Helper()
if client == nil {
client = &stubProviderClient{}
}
svc := NewTenantSandboxConfigService(repo, agents, testGlobalSandboxConfig())
svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return client, nil
}
return svc
}
// An identity change while sandboxes are alive must be refused, and the stored
// credentials must remain untouched so cleanup stays possible.
func TestUpdateRefusesIdentityChangeWhileSandboxesLive(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
{ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
}}}, stubAgentRepo{})
_, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod",
Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
})
require.ErrorIs(t, err, ErrSandboxesStillLive)
require.Nil(t, repo.updated, "credentials must not be overwritten")
require.Equal(t, []string{"get", "cordon", "uncordon"}, repo.events,
"the cordon must be committed before the inventory check and released after")
}
// With no live sandboxes the write proceeds, and the cordon brackets it.
func TestUpdateIdentityChangeCordonsThenWrites(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
_, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod",
Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
})
require.NoError(t, err)
require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
}
// A non-identity edit must not pay for a cordon or a provider round-trip.
func TestUpdateNonIdentityEditSkipsCordon(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
client := &stubProviderClient{}
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, client, stubAgentRepo{})
_, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod renamed",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),
})
require.NoError(t, err)
require.Equal(t, []string{"get", "write"}, repo.events)
require.Equal(t, "prod renamed", repo.updated.Name)
require.Equal(t, 0, client.listCalls)
}
func TestUpdateRefusalCarriesInventory(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
{ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
{ID: "sb-2", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-2"}},
}}}, stubAgentRepo{names: []string{"analyst", "writer"}})
_, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod",
Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
})
var liveErr *SandboxesStillLiveError
require.ErrorAs(t, err, &liveErr)
require.Equal(t, 2, liveErr.Inventory.SandboxCount)
require.ElementsMatch(t, []string{"s-1", "s-2"}, liveErr.Inventory.SessionIDs)
require.Equal(t, []string{"analyst", "writer"}, liveErr.Inventory.AgentNames)
}
func TestUpdateSweepsSandboxCreatedDuringCordonWindow(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
ctx, cancel := context.WithCancel(context.Background())
client := &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{
nil,
{{ID: "sb-race", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-race"}}},
}}
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}, onUpdate: cancel}
svc := newTestConfigService(t, repo, client, stubAgentRepo{})
_, err := svc.Update(ctx, 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod",
Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
})
require.NoError(t, err)
require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
require.Equal(t, []string{"sb-race"}, client.deleted)
require.NoError(t, client.deleteCtxErr, "post-write sweep must survive request cancellation")
}
func TestUpdateClearsCordonWhenRequestContextCancelled(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
ctx, cancel := context.WithCancel(context.Background())
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}, onSetCordon: cancel}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
_, err := svc.Update(ctx, 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod",
Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
})
require.NoError(t, err)
require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
require.NoError(t, repo.clearCordonCtxErr, "cordon release must survive request cancellation")
}
func TestDeleteRefusesWhileSandboxesLive(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
{ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
}}}, stubAgentRepo{names: []string{"analyst"}})
err := svc.Delete(context.Background(), 7, "cfg-a", false)
require.ErrorIs(t, err, ErrSandboxesStillLive)
var liveErr *SandboxesStillLiveError
require.ErrorAs(t, err, &liveErr)
require.Equal(t, 1, liveErr.Inventory.SandboxCount)
require.Equal(t, []string{"s-1"}, liveErr.Inventory.SessionIDs)
require.Equal(t, []string{"analyst"}, liveErr.Inventory.AgentNames)
require.False(t, repo.deleted)
require.Equal(t, []string{"get"}, repo.events)
}
// "We cannot tell" must not read as "nothing there": refuse, and say which of
// the two it is, because only this one is force-overridable.
func TestDeleteRefusesWhenInventoryUnverifiable(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return nil, stderrors.New("dial tcp: no such host")
}
err := svc.Delete(context.Background(), 7, "cfg-a", false)
require.ErrorIs(t, err, ErrSandboxInventoryUnverifiable)
require.NotErrorIs(t, err, ErrSandboxesStillLive)
require.False(t, repo.deleted)
}
// Deletion has no "create a second config" way out, so a config whose endpoint
// vanished must remain removable once an admin takes responsibility.
func TestDeleteForceRemovesConfigWithUnverifiableInventory(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return nil, stderrors.New("dial tcp: no such host")
}
require.NoError(t, svc.Delete(context.Background(), 7, "cfg-a", true))
require.True(t, repo.deleted)
}
// force covers "cannot verify", never "verified live". Letting it through here
// would strand paused sandboxes nobody can reach again - the exact leak this
// whole flow exists to prevent.
func TestDeleteForceStillRefusesVerifiedLiveSandboxes(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, &stubProviderClient{inventories: [][]sandbox.RemoteSandboxSummary{{
{ID: "sb-1", Metadata: map[string]string{sandbox.MetadataSessionIDKey(): "s-1"}},
}}}, stubAgentRepo{})
err := svc.Delete(context.Background(), 7, "cfg-a", true)
require.ErrorIs(t, err, ErrSandboxesStillLive)
require.False(t, repo.deleted)
}
// The card still has to render, and the agent warning comes from our own DB, so
// an unreachable provider is a flag rather than an error.
func TestInventoryMarksUnverifiableInsteadOfFailing(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{names: []string{"analyst"}})
svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return nil, stderrors.New("dial tcp: no such host")
}
inv, err := svc.Inventory(context.Background(), 7, "cfg-a")
require.NoError(t, err)
require.True(t, inv.Unverifiable)
require.Zero(t, inv.SandboxCount)
require.Equal(t, []string{"analyst"}, inv.AgentNames)
}
// When old credentials cannot reach the provider, the update proceeds anyway
// so the admin can fix a mistyped key; sandboxes_still_live still blocks when
// the old credentials can list live instances.
func TestUpdateProceedsWhenInventoryUnverifiable(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return nil, stderrors.New("dial tcp: no such host")
}
updated, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod",
Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
})
require.NoError(t, err)
require.NotNil(t, updated)
require.NotNil(t, repo.updated)
require.Equal(t, "key-b", repo.updated.Config.E2B.APIKey)
require.Equal(t, []string{"get", "cordon", "write", "uncordon"}, repo.events)
}
func TestDeleteSoftDeletesWhenEmpty(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
err := svc.Delete(context.Background(), 7, "cfg-a", false)
require.NoError(t, err)
require.True(t, repo.deleted)
require.Equal(t, []string{"get", "delete"}, repo.events)
}
// Reporting success for a config that is not there would let the UI drop a card
// the workspace still has, and hide a wrong ID from the caller.
func TestDeleteAndInventoryReportMissingConfig(t *testing.T) {
repo := &fakeConfigRepo{}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
ctx := context.Background()
err := svc.Delete(ctx, 7, "cfg-missing", false)
var appErr *apperrors.AppError
require.ErrorAs(t, err, &appErr)
require.Equal(t, http.StatusNotFound, appErr.HTTPCode)
require.False(t, repo.deleted)
_, err = svc.Inventory(ctx, 7, "cfg-missing")
require.ErrorAs(t, err, &appErr)
require.Equal(t, http.StatusNotFound, appErr.HTTPCode)
}
func TestSanitizeSandboxConfigPreservesRedactedSecret(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
existing := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIKey: "stored-key", APIURL: "https://203.0.113.10", TemplateID: "t1",
},
}
incoming := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIKey: types.RedactedSecretPlaceholder,
APIURL: "https://203.0.113.10",
TemplateID: "t1",
},
}
out, err := SanitizeSandboxConfig(incoming, existing)
require.NoError(t, err)
require.Equal(t, "stored-key", out.E2B.APIKey)
}
// Nothing is inherited from the deployment, so an incomplete config has to be
// refused when it is saved rather than at the first sandbox allocation.
func TestSanitizeSandboxConfigRejectsIncompleteConfig(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
incoming := &types.TenantSandboxConfig{
SandboxType: "cube",
Cube: &types.CubeSandboxConfig{APIURL: "https://203.0.113.10"},
}
_, err := SanitizeSandboxConfig(incoming, nil)
require.ErrorIs(t, err, sandbox.ErrSandboxConfigIncomplete)
require.Contains(t, err.Error(), "proxy_url")
}
// A masked key must still count as present: the merge restores it before the
// completeness check runs, otherwise every edit of a saved config would be
// rejected for a missing credential it never stopped having.
func TestSanitizeSandboxConfigCountsRedactedSecretAsPresent(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
existing := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "stored-key", TemplateID: "t1"},
}
incoming := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIKey: types.RedactedSecretPlaceholder, TemplateID: "t2",
},
}
out, err := SanitizeSandboxConfig(incoming, existing)
require.NoError(t, err)
require.Equal(t, "t2", out.E2B.TemplateID)
}
func TestSanitizeSandboxConfigRejectsUnsafeURL(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
incoming := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIURL: "http://169.254.169.254"},
}
_, err := SanitizeSandboxConfig(incoming, nil)
require.ErrorIs(t, err, sandbox.ErrUnsafeOutboundURL)
}
func TestSanitizeSandboxConfigRejectsUnknownType(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
incoming := &types.TenantSandboxConfig{SandboxType: "quantum"}
_, err := SanitizeSandboxConfig(incoming, nil)
require.Error(t, err)
}
// Without an AES key the Value() hook would write these secrets as plaintext,
// so saving must be refused rather than silently downgrading storage security.
func TestSanitizeSandboxConfigRefusesSecretsWithoutAESKey(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", "")
incoming := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "plaintext-risk"},
}
_, err := SanitizeSandboxConfig(incoming, nil)
require.Error(t, err)
// A config without secrets is still allowed in that deployment.
_, err = SanitizeSandboxConfig(&types.TenantSandboxConfig{SandboxType: "local"}, nil)
require.NoError(t, err)
}
func TestSandboxesStillLiveErrorSupportsErrorsIs(t *testing.T) {
err := &SandboxesStillLiveError{Inventory: SandboxInventory{SandboxCount: 1}}
require.True(t, stderrors.Is(err, ErrSandboxesStillLive))
}
func TestCreateRejectsNonNamedSandboxBackend(t *testing.T) {
svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})
_, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{
Name: "local-dev",
Config: &types.TenantSandboxConfig{SandboxType: "local"},
})
require.ErrorIs(t, err, ErrNamedSandboxBackendUnsupported)
}
func TestWorkspaceScriptsDisabledPolicy(t *testing.T) {
repo := &fakeConfigRepo{}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
ctx := context.Background()
disabled, err := svc.WorkspaceScriptsDisabled(ctx, 7)
require.NoError(t, err)
require.False(t, disabled)
require.NoError(t, svc.SetWorkspaceScriptsDisabled(ctx, 7, true))
disabled, err = svc.WorkspaceScriptsDisabled(ctx, 7)
require.NoError(t, err)
require.True(t, disabled)
list, err := svc.List(ctx, 7)
require.NoError(t, err)
require.Empty(t, list)
require.NoError(t, svc.SetWorkspaceScriptsDisabled(ctx, 7, false))
disabled, err = svc.WorkspaceScriptsDisabled(ctx, 7)
require.NoError(t, err)
require.False(t, disabled)
}

View File

@ -0,0 +1,124 @@
// Package service - per-tenant sandbox resolution helpers.
//
// The sandbox package must not depend on repositories, so the config lookup is
// adapted here and injected as sandbox.TenantSandboxConfigLoader.
package service
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// tenantSandboxConfigLoader reads one named sandbox config for a workspace.
type tenantSandboxConfigLoader struct {
repo repository.TenantSandboxConfigRepository
now func() time.Time
}
// NewTenantSandboxConfigLoader adapts the config repository onto the sandbox
// package's loader contract.
func NewTenantSandboxConfigLoader(
repo repository.TenantSandboxConfigRepository,
) sandbox.TenantSandboxConfigLoader {
return &tenantSandboxConfigLoader{repo: repo, now: time.Now}
}
// Load reports whether the config exists and whether it is currently cordoned.
// A cordon is honoured here - the single choke point every sandbox operation
// passes through - so no new sandbox can be created on credentials that are
// about to be replaced.
func (l *tenantSandboxConfigLoader) Load(
ctx context.Context,
tenantID uint64,
configID string,
) (sandbox.ResolvedTenantSandboxConfig, error) {
if l.repo == nil {
return sandbox.ResolvedTenantSandboxConfig{}, nil
}
entity, err := l.repo.GetByID(ctx, tenantID, configID)
if err != nil {
return sandbox.ResolvedTenantSandboxConfig{}, err
}
if entity == nil {
return sandbox.ResolvedTenantSandboxConfig{Found: false}, nil
}
return sandbox.ResolvedTenantSandboxConfig{
Config: entity.Config,
Found: true,
Cordoned: entity.IsCordoned(l.now(), types.SandboxCordonLease),
}, nil
}
// WorkspaceSandboxPolicy reports whether sandbox execution is disabled for the
// entire workspace, including agents bound to named cube/e2b configs.
type WorkspaceSandboxPolicy interface {
WorkspaceScriptsDisabled(ctx context.Context, tenantID uint64) (bool, error)
}
func deploymentSandboxDisabled() bool {
mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
return mode == "" || mode == "disabled"
}
// resolveTenantSandboxForConfig returns the Manager for an explicit config.
//
// Unlike the previous tenant-only helper this does NOT degrade to the default
// manager on error: with several configs per workspace, a silent substitution
// would run scripts on a different backend than the one selected - and then
// artifact collection and sandbox teardown would target the wrong account.
func resolveTenantSandboxForConfig(
ctx context.Context,
resolver sandbox.TenantSandboxResolver,
fallback sandbox.Manager,
tenantID uint64,
configID string,
policy WorkspaceSandboxPolicy,
) (sandbox.Manager, error) {
// ① Deployment-wide kill switch (WEKNORA_SANDBOX_MODE empty/disabled).
if deploymentSandboxDisabled() {
return sandbox.NewDisabledManager(), nil
}
// ② Workspace kill switch — independent of resolver availability.
if policy != nil && tenantID != 0 {
disabled, err := policy.WorkspaceScriptsDisabled(ctx, tenantID)
if err != nil {
logger.Warnf(ctx,
"[sandbox] failed to read workspace sandbox policy for %d: %v",
tenantID, err)
} else if disabled {
return sandbox.NewDisabledManager(), nil
}
}
// ③ Default path: agents with no named config use the process-wide manager.
if configID == "" || configID == types.SandboxConfigIDGlobalDefault {
return fallback, nil
}
// ④ Named config: must not silently fall back to the deployment default.
if tenantID == 0 {
return nil, fmt.Errorf(
"sandbox: resolve config %q: missing workspace context", configID)
}
if resolver == nil {
return nil, fmt.Errorf(
"sandbox: resolve config %q: per-tenant resolver unavailable", configID)
}
mgr, err := resolver.Resolve(ctx, tenantID, configID)
if err != nil {
logger.Warnf(ctx,
"[sandbox] failed to resolve config %q for workspace %d: %v",
configID, tenantID, err)
return nil, err
}
return mgr, nil
}

View File

@ -0,0 +1,280 @@
// Package redislock provides token-owned Redis locks with atomic renewal and
// release. Callers must treat loss of ownership as loss of exclusive access.
package redislock
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
const releaseTimeout = 5 * time.Second
// ErrLockOwnershipLost means exclusive ownership can no longer be guaranteed.
var ErrLockOwnershipLost = errors.New("redis lock ownership lost")
type ownershipContextKey struct{}
var (
releaseScript = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`)
renewScript = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('PEXPIRE', KEYS[1], ARGV[2])
end
return 0
`)
)
// OwnershipContext returns a context that is canceled only when lock
// ownership is lost, not when the request context is canceled. Outside a
// renewable-lock callback it falls back to a cancellation-detached context.
func OwnershipContext(ctx context.Context) context.Context {
if ctx == nil {
return context.Background()
}
if ownershipCtx, ok := ctx.Value(ownershipContextKey{}).(context.Context); ok {
return ownershipCtx
}
return context.WithoutCancel(ctx)
}
// NewToken returns a random owner token suitable for compare-and-* scripts.
func NewToken() (string, error) {
var token [16]byte
if _, err := rand.Read(token[:]); err != nil {
return "", fmt.Errorf("generate redis lock token: %w", err)
}
return hex.EncodeToString(token[:]), nil
}
// TryAcquire attempts one SET NX acquisition.
func TryAcquire(
ctx context.Context,
client redis.UniversalClient,
key string,
token string,
lease time.Duration,
) (bool, error) {
if err := validateOperation(client, key, token, lease); err != nil {
return false, err
}
acquired, err := client.SetNX(ctx, key, token, lease).Result()
if err != nil {
return false, fmt.Errorf("acquire redis lock %q: %w", key, err)
}
return acquired, nil
}
// Acquire waits until the lock is acquired or ctx is cancelled.
func Acquire(
ctx context.Context,
client redis.UniversalClient,
key string,
token string,
lease time.Duration,
) error {
for {
acquired, err := TryAcquire(ctx, client, key, token, lease)
if err != nil {
return err
}
if acquired {
return nil
}
timer := time.NewTimer(retryDelay())
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return ctx.Err()
case <-timer.C:
}
}
}
// Release deletes the lock only if token still owns it.
func Release(
ctx context.Context,
client redis.UniversalClient,
key string,
token string,
) (bool, error) {
if client == nil {
return false, errors.New("redis client is required")
}
if key == "" || token == "" {
return false, errors.New("redis lock key and token are required")
}
released, err := releaseScript.Run(ctx, client, []string{key}, token).Int64()
if err != nil {
return false, fmt.Errorf("release redis lock %q: %w", key, err)
}
return released != 0, nil
}
// Renew extends the lease only if token still owns the lock.
func Renew(
ctx context.Context,
client redis.UniversalClient,
key string,
token string,
lease time.Duration,
) (bool, error) {
if err := validateOperation(client, key, token, lease); err != nil {
return false, err
}
renewed, err := renewScript.Run(
ctx,
client,
[]string{key},
token,
lease.Milliseconds(),
).Int64()
if err != nil {
return false, fmt.Errorf("renew redis lock %q: %w", key, err)
}
return renewed != 0, nil
}
// WithRenewableLock acquires key, renews it while fn runs, and atomically
// releases it on exit. Renewal failure cancels the context passed to fn.
func WithRenewableLock(
ctx context.Context,
client redis.UniversalClient,
key string,
lease time.Duration,
renewInterval time.Duration,
fn func(context.Context) error,
) (resultErr error) {
if fn == nil {
return errors.New("redis lock callback is required")
}
if renewInterval <= 0 || renewInterval >= lease {
return errors.New("redis lock renewal interval must be positive and shorter than the lease")
}
token, err := NewToken()
if err != nil {
return err
}
if err := Acquire(ctx, client, key, token, lease); err != nil {
return err
}
lockCtx, cancelLock := context.WithCancelCause(ctx)
ownershipCtx, cancelOwnership := context.WithCancelCause(context.Background())
lockCtx = context.WithValue(lockCtx, ownershipContextKey{}, ownershipCtx)
renewCtx, stopRenewal := context.WithCancel(context.WithoutCancel(ctx))
renewResult := make(chan error, 1)
go renewLoop(
renewCtx,
cancelLock,
cancelOwnership,
client,
key,
token,
lease,
renewInterval,
renewResult,
)
defer func() {
stopRenewal()
renewErr := <-renewResult
cancelLock(nil)
cancelOwnership(nil)
releaseCtx, cancelRelease := context.WithTimeout(context.Background(), releaseTimeout)
released, releaseErr := Release(releaseCtx, client, key, token)
cancelRelease()
if releaseErr == nil && !released && renewErr == nil {
releaseErr = fmt.Errorf("%w for %q", ErrLockOwnershipLost, key)
}
resultErr = errors.Join(resultErr, renewErr, ctx.Err(), releaseErr)
}()
resultErr = fn(lockCtx)
return resultErr
}
func renewLoop(
ctx context.Context,
cancelLock context.CancelCauseFunc,
cancelOwnership context.CancelCauseFunc,
client redis.UniversalClient,
key string,
token string,
lease time.Duration,
renewInterval time.Duration,
result chan<- error,
) {
ticker := time.NewTicker(renewInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
result <- nil
return
case <-ticker.C:
renewed, err := Renew(ctx, client, key, token, lease)
if err != nil {
if errors.Is(err, context.Canceled) && ctx.Err() != nil {
result <- nil
return
}
ownershipErr := fmt.Errorf("%w: %w", ErrLockOwnershipLost, err)
cancelOwnership(ownershipErr)
cancelLock(ownershipErr)
result <- ownershipErr
return
}
if !renewed {
ownershipErr := fmt.Errorf("%w for %q", ErrLockOwnershipLost, key)
cancelOwnership(ownershipErr)
cancelLock(ownershipErr)
result <- ownershipErr
return
}
}
}
}
func validateOperation(
client redis.UniversalClient,
key string,
token string,
lease time.Duration,
) error {
if client == nil {
return errors.New("redis client is required")
}
if key == "" || token == "" {
return errors.New("redis lock key and token are required")
}
if lease <= 0 {
return errors.New("redis lock lease must be positive")
}
return nil
}
func retryDelay() time.Duration {
var random [1]byte
if _, err := rand.Read(random[:]); err != nil {
return 50 * time.Millisecond
}
return 25*time.Millisecond + time.Duration(random[0])%50*time.Millisecond
}

View File

@ -0,0 +1,237 @@
package redislock_test
import (
"context"
"errors"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/common/redislock"
)
func newTokenLockTestClient(t *testing.T) (*redis.Client, *miniredis.Miniredis) {
t.Helper()
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
t.Cleanup(func() { require.NoError(t, client.Close()) })
return client, mini
}
func TestNewTokenReturnsUniqueOpaqueOwners(t *testing.T) {
t.Parallel()
first, err := redislock.NewToken()
require.NoError(t, err)
second, err := redislock.NewToken()
require.NoError(t, err)
require.Len(t, first, 32)
require.Len(t, second, 32)
require.NotEqual(t, first, second)
}
func TestTokenLockAcquireAndReleaseRequiresOwnership(t *testing.T) {
client, _ := newTokenLockTestClient(t)
ctx := context.Background()
key := "lock:ownership"
acquired, err := redislock.TryAcquire(ctx, client, key, "owner-a", time.Minute)
require.NoError(t, err)
require.True(t, acquired)
acquired, err = redislock.TryAcquire(ctx, client, key, "owner-b", time.Minute)
require.NoError(t, err)
require.False(t, acquired)
released, err := redislock.Release(ctx, client, key, "owner-b")
require.NoError(t, err)
require.False(t, released)
require.Equal(t, "owner-a", client.Get(ctx, key).Val())
released, err = redislock.Release(ctx, client, key, "owner-a")
require.NoError(t, err)
require.True(t, released)
require.ErrorIs(t, client.Get(ctx, key).Err(), redis.Nil)
}
func TestTokenLockRenewRequiresOwnership(t *testing.T) {
client, mini := newTokenLockTestClient(t)
ctx := context.Background()
key := "lock:renew"
require.NoError(t, client.Set(ctx, key, "owner-a", time.Second).Err())
renewed, err := redislock.Renew(ctx, client, key, "owner-b", time.Minute)
require.NoError(t, err)
require.False(t, renewed)
renewed, err = redislock.Renew(ctx, client, key, "owner-a", time.Minute)
require.NoError(t, err)
require.True(t, renewed)
mini.FastForward(2 * time.Second)
require.Equal(t, "owner-a", client.Get(ctx, key).Val())
}
func TestTokenLockRejectsUnsafeLeaseConfiguration(t *testing.T) {
client, _ := newTokenLockTestClient(t)
ctx := context.Background()
_, err := redislock.TryAcquire(ctx, client, "lock:key", "owner", 0)
require.Error(t, err)
_, err = redislock.Renew(ctx, client, "lock:key", "owner", -time.Second)
require.Error(t, err)
err = redislock.WithRenewableLock(
ctx,
client,
"lock:key",
time.Second,
time.Second,
func(context.Context) error { return nil },
)
require.Error(t, err)
}
func TestWithRenewableLockReturnsCallbackErrorAndReleases(t *testing.T) {
client, _ := newTokenLockTestClient(t)
ctx := context.Background()
key := "lock:callback"
want := errors.New("callback failed")
err := redislock.WithRenewableLock(
ctx,
client,
key,
time.Minute,
20*time.Second,
func(context.Context) error { return want },
)
require.ErrorIs(t, err, want)
require.ErrorIs(t, client.Get(ctx, key).Err(), redis.Nil)
}
func TestWithRenewableLockHonorsContextWhileWaiting(t *testing.T) {
client, _ := newTokenLockTestClient(t)
ctx := context.Background()
key := "lock:busy"
require.NoError(t, client.Set(ctx, key, "owner-a", time.Minute).Err())
waitCtx, cancel := context.WithTimeout(ctx, 25*time.Millisecond)
defer cancel()
called := false
err := redislock.WithRenewableLock(
waitCtx,
client,
key,
time.Minute,
20*time.Second,
func(context.Context) error {
called = true
return nil
},
)
require.ErrorIs(t, err, context.DeadlineExceeded)
require.False(t, called)
}
func TestWithRenewableLockCancelsCallbackAfterOwnershipLoss(t *testing.T) {
client, _ := newTokenLockTestClient(t)
key := "lock:lost"
err := redislock.WithRenewableLock(
context.Background(),
client,
key,
100*time.Millisecond,
10*time.Millisecond,
func(lockCtx context.Context) error {
require.NoError(t, client.Set(context.Background(), key, "replacement", time.Minute).Err())
select {
case <-lockCtx.Done():
return nil
case <-time.After(time.Second):
return errors.New("callback was not cancelled")
}
},
)
require.Error(t, err)
require.Contains(t, err.Error(), "ownership lost")
require.Equal(t, "replacement", client.Get(context.Background(), key).Val())
}
func TestWithRenewableLockReportsOwnershipLossAtRelease(t *testing.T) {
client, _ := newTokenLockTestClient(t)
key := "lock:lost-before-renewal"
err := redislock.WithRenewableLock(
context.Background(),
client,
key,
time.Minute,
20*time.Second,
func(context.Context) error {
return client.Set(context.Background(), key, "replacement", time.Minute).Err()
},
)
require.Error(t, err)
require.Contains(t, err.Error(), "ownership lost")
require.Equal(t, "replacement", client.Get(context.Background(), key).Val())
}
func TestOwnershipContextSurvivesCallerCancellation(t *testing.T) {
client, _ := newTokenLockTestClient(t)
ctx, cancel := context.WithCancel(context.Background())
err := redislock.WithRenewableLock(
ctx,
client,
"lock:caller-cancel",
time.Minute,
20*time.Second,
func(lockCtx context.Context) error {
ownershipCtx := redislock.OwnershipContext(lockCtx)
cancel()
require.ErrorIs(t, lockCtx.Err(), context.Canceled)
select {
case <-ownershipCtx.Done():
t.Fatal("caller cancellation must not imply lock ownership loss")
default:
}
return nil
},
)
require.ErrorIs(t, err, context.Canceled)
}
func TestOwnershipContextCancelsWhenRenewalLosesOwnership(t *testing.T) {
client, _ := newTokenLockTestClient(t)
key := "lock:ownership-context"
err := redislock.WithRenewableLock(
context.Background(),
client,
key,
100*time.Millisecond,
10*time.Millisecond,
func(lockCtx context.Context) error {
ownershipCtx := redislock.OwnershipContext(lockCtx)
require.NoError(t, client.Set(context.Background(), key, "replacement", time.Minute).Err())
select {
case <-ownershipCtx.Done():
return nil
case <-time.After(time.Second):
return errors.New("ownership context was not cancelled")
}
},
)
require.ErrorIs(t, err, redislock.ErrLockOwnershipLost)
}

View File

@ -161,6 +161,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewMCPServiceRepository))
must(container.Provide(repository.NewMCPToolApprovalRepository))
must(container.Provide(repository.NewMCPOAuthRepository))
must(container.Provide(repository.NewTenantSandboxConfigRepository))
must(container.Provide(repository.NewCustomAgentRepository))
must(container.Provide(repository.NewOrganizationRepository))
must(container.Provide(repository.NewKBShareRepository))
@ -180,6 +181,19 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(mcp.NewMCPManager))
must(container.Provide(mcp.NewOAuthManager))
// Sandbox manager (script execution backend for skills). Reads
// WEKNORA_SANDBOX_MODE env var: "docker" | "local" | "cube" | "disabled"
// (default). The Cube mode wires a SessionBoundManager so each Session
// gets its own persistent MicroVM. See internal/sandbox/session_manager.go.
logger.Debugf(ctx, "[Container] Registering sandbox manager...")
must(container.Provide(newSandboxManager))
// Per-tenant sandbox backends: the resolver builds a manager per request
// from the tenant's own configuration, falling back to the singleton above
// for tenants that configured nothing.
must(container.Provide(service.NewTenantSandboxConfigLoader))
must(container.Provide(newTenantSandboxResolver))
must(container.Provide(newSandboxConfigDefaults))
// Business service layer
logger.Debugf(ctx, "[Container] Registering business services...")
must(container.Provide(service.NewTenantService))
@ -202,6 +216,15 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewEvaluationService))
must(container.Provide(service.NewUserService))
must(container.Provide(service.NewSystemSettingService))
must(container.Provide(func(
repo repository.TenantSandboxConfigRepository,
agents interfaces.CustomAgentRepository,
) *service.TenantSandboxConfigService {
return service.NewTenantSandboxConfigService(repo, agents, buildGlobalSandboxConfig())
}))
must(container.Provide(func(s *service.TenantSandboxConfigService) service.WorkspaceSandboxPolicy {
return s
}))
must(container.Provide(service.NewWeKnoraCloudService))
// Extract services - register individual extracters with names
@ -256,6 +279,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
// SessionService is passed as parameter to CreateAgentEngine method when creating AgentService
logger.Debugf(ctx, "[Container] Registering event bus and agent service...")
must(container.Provide(event.NewEventBus))
must(container.Provide(service.NewSessionSandboxPinner))
must(container.Provide(func(cfg *config.Config, s interfaces.MCPToolApprovalService, rdb *redis.Client) *approval.Gate {
return approval.NewGate(cfg, &approval.Adapter{Svc: s}, rdb)
}))
@ -268,6 +292,13 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering session service...")
must(container.Provide(service.NewSessionService))
// ArtifactCollector drains skill-generated files from the sandbox on
// each agent turn (see spec at
// docs/superpowers/specs/2026-07-10-skill-artifact-download-design.md).
// The factory returns nil when the sandbox backend does not support
// per-session file inspection; downstream code guards on nil.
must(container.Provide(service.NewArtifactCollectorFromSandboxManager))
logger.Debugf(ctx, "[Container] Registering task enqueuer...")
redisAvailable := os.Getenv("REDIS_ADDR") != ""
if redisAvailable {
@ -352,6 +383,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewMessageHandler))
must(container.Provide(handler.NewMessageSuggestionHandler))
must(container.Provide(handler.NewModelHandler))
must(container.Provide(handler.NewSandboxConfigHandler))
must(container.Provide(handler.NewEvaluationHandler))
must(container.Provide(handler.NewInitializationHandler))
must(container.Provide(handler.NewAuthHandler))

View File

@ -0,0 +1,294 @@
// Package container - sandbox provider.
//
// This file wires up the sandbox.Manager singleton that gets injected into
// agent_service and session_service. It is intentionally isolated from
// container.go so environment-variable parsing and provider-specific
// configuration stay out of the main provider table.
package container
import (
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// newSandboxManager builds a sandbox.Manager from environment variables.
// Recognised variables:
//
// WEKNORA_SANDBOX_MODE "docker" | "local" | "cube" | "e2b" | "disabled" (default "disabled")
// WEKNORA_SANDBOX_TIMEOUT per-execute timeout in seconds (default 60)
// WEKNORA_SANDBOX_DOCKER_IMAGE custom docker image (docker mode only)
// WEKNORA_SANDBOX_REDIS_NAMESPACE Redis key namespace suffix (default derives from
// WEKNORA_REDIS_NAMESPACE, then "weknora")
// WEKNORA_SANDBOX_CUBE_API_URL CubeAPI endpoint (default http://127.0.0.1:33000)
// WEKNORA_SANDBOX_CUBE_PROXY_URL CubeProxy endpoint (envd) (default http://127.0.0.1:80)
// WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN sandbox routing domain (default cube.app)
// WEKNORA_SANDBOX_CUBE_ENVD_PORT internal envd port (default 49983)
// WEKNORA_SANDBOX_CUBE_API_KEY X-API-Key value (default empty; Cube auth disabled)
// WEKNORA_SANDBOX_CUBE_TEMPLATE template ID (default tpl-2b7911a5c3bb419a8745957a)
// WEKNORA_SANDBOX_CUBE_SANDBOX_TTL Cube-side sandbox timeout, seconds (default 1800)
// WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT single HTTP call timeout, seconds (default 30)
// WEKNORA_SANDBOX_E2B_API_KEY X-API-Key for the E2B backend (required for mode=e2b)
// WEKNORA_SANDBOX_E2B_API_URL E2B control-plane endpoint (default https://api.e2b.app)
// WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN sandbox routing domain (default e2b.app)
// WEKNORA_SANDBOX_E2B_TEMPLATE template ID / alias
// WEKNORA_SANDBOX_E2B_SANDBOX_TTL E2B-side idle timeout, seconds (default 300)
// WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT single HTTP call timeout, seconds (default 30)
func newSandboxManager(
redisClient *redis.Client,
sessionRepo interfaces.SessionRepository,
) sandbox.Manager {
ctx := context.Background()
mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))
if mode == "" {
mode = "disabled"
}
switch mode {
case "docker":
dockerImage := os.Getenv("WEKNORA_SANDBOX_DOCKER_IMAGE")
if dockerImage == "" {
dockerImage = sandbox.DefaultDockerImage
}
m, err := sandbox.NewManagerFromType("docker", true, dockerImage)
if err != nil {
logger.Warnf(ctx, "Failed to initialize Docker sandbox, falling back to disabled: %v", err)
return sandbox.NewDisabledManager()
}
logger.Infof(ctx, "Sandbox configured: mode=docker image=%s", dockerImage)
return m
case "local":
m, err := sandbox.NewManagerFromType("local", false, "")
if err != nil {
logger.Warnf(ctx, "Failed to initialize local sandbox: %v", err)
return sandbox.NewDisabledManager()
}
logger.Infof(ctx, "Sandbox configured: mode=local")
return m
case "cube":
return buildCubeManager(ctx, redisClient, sessionRepo)
case "e2b":
return buildE2BManager(ctx, redisClient, sessionRepo)
default:
logger.Infof(ctx, "Sandbox configured: mode=disabled")
return sandbox.NewDisabledManager()
}
}
func buildCubeManager(
ctx context.Context,
redisClient *redis.Client,
sessionRepo interfaces.SessionRepository,
) sandbox.Manager {
cfg := sandbox.CubeConfigFromEnv()
// The pool lives as long as this process-wide manager, and its guarded
// dialer keeps the deployment default on the same outbound policy the
// per-tenant resolver enforces.
client, err := sandbox.NewCubeRemoteClientWithPool(cfg, sandbox.NewCubeTransportPool(nil))
if err != nil {
logger.Warnf(ctx, "Failed to build Cube sandbox client: %v (falling back to disabled)", err)
return sandbox.NewDisabledManager()
}
store, storeKind, err := selectSessionBindingStore(redisClient, true)
if err != nil {
logger.Errorf(ctx, "Refusing to start Cube sandbox: %v", err)
return sandbox.NewDisabledManager()
}
m, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: store,
Checker: sessionExistenceCheckerFor(sessionRepo),
})
if err != nil {
logger.Warnf(ctx, "Failed to initialize Cube sandbox: %v (falling back to disabled)", err)
return sandbox.NewDisabledManager()
}
logger.Infof(ctx,
"Sandbox configured: mode=cube api=%s proxy=%s domain=%s template=%s binding=%s",
cfg.CubeAPIURL, cfg.CubeProxyURL, cfg.CubeSandboxDomain, cfg.CubeTemplate, storeKind,
)
return m
}
func buildE2BManager(
ctx context.Context,
redisClient *redis.Client,
sessionRepo interfaces.SessionRepository,
) sandbox.Manager {
cfg := sandbox.E2BConfigFromEnv()
client, err := sandbox.NewE2BRemoteClientWithTransport(cfg, sandbox.NewGuardedTransport())
if err != nil {
logger.Warnf(ctx, "Failed to build E2B sandbox client: %v (falling back to disabled)", err)
return sandbox.NewDisabledManager()
}
store, storeKind, err := selectSessionBindingStore(redisClient, true)
if err != nil {
logger.Errorf(ctx, "Refusing to start E2B sandbox: %v", err)
return sandbox.NewDisabledManager()
}
m, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: store,
Checker: sessionExistenceCheckerFor(sessionRepo),
})
if err != nil {
logger.Warnf(ctx, "Failed to initialize E2B sandbox: %v (falling back to disabled)", err)
return sandbox.NewDisabledManager()
}
logger.Infof(ctx,
"Sandbox configured: mode=e2b api=%s domain=%s template=%s ttl=%s binding=%s",
cfg.E2BAPIURL, cfg.E2BSandboxDomain, cfg.E2BTemplate, cfg.E2BSandboxTTL, storeKind,
)
return m
}
func selectSessionBindingStore(
redisClient *redis.Client,
requireRedis bool,
) (sandbox.SessionSandboxBindingStore, string, error) {
namespace := strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_REDIS_NAMESPACE"))
if namespace == "" {
namespace = strings.TrimSpace(os.Getenv("WEKNORA_REDIS_NAMESPACE"))
}
if namespace == "" {
namespace = "weknora"
}
if redisClient != nil {
store, err := sandbox.NewRedisSessionSandboxBindingStore(redisClient, namespace)
if err != nil {
return nil, "", fmt.Errorf("build redis binding store: %w", err)
}
return store, "redis", nil
}
if requireRedis && !allowMemorySandboxBinding() {
return nil, "", errors.New(
"remote sandbox modes (cube/e2b) require Redis for session binding; " +
"set WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true only for single-instance dev",
)
}
logger.Warnf(context.Background(),
"[sandbox] No Redis configured, using in-memory binding store (single-instance)")
return sandbox.NewMemorySessionSandboxBindingStore(), "memory", nil
}
func allowMemorySandboxBinding() bool {
return strings.EqualFold(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING")), "true")
}
// sessionExistenceLookup is the narrow slice of SessionRepository the
// session existence checker actually needs. Declaring it here (rather than
// depending on interfaces.SessionRepository) keeps the checker easy to test
// and lets the container inject a nil repository in Lite mode without
// dragging the whole database contract along.
type sessionExistenceLookup interface {
GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)
}
// sessionExistenceCheckerFor returns a SessionExistenceChecker backed by the
// tenant session repository. When the repository is unavailable (Lite mode
// without a database) the returned checker is permissive so single-process
// deployments still work; multi-instance production paths always resolve a
// real repository because the container refuses to boot without one.
func sessionExistenceCheckerFor(
lookup sessionExistenceLookup,
) sandbox.SessionExistenceChecker {
if lookup == nil {
return sandbox.PermissiveSessionExistenceChecker{}
}
return &repositorySessionExistenceChecker{lookup: lookup}
}
// repositorySessionExistenceChecker adapts SessionRepository.GetByID onto the
// SessionExistenceChecker contract. gorm.ErrRecordNotFound → false, other
// errors propagate so the lifecycle coordinator preserves bindings under
// transient database failures.
type repositorySessionExistenceChecker struct {
lookup sessionExistenceLookup
}
func (c *repositorySessionExistenceChecker) SessionExists(
ctx context.Context,
key sandbox.SessionSandboxKey,
) (bool, error) {
if c == nil || c.lookup == nil {
return true, nil
}
session, err := c.lookup.GetByID(ctx, key.TenantID, key.SessionID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, apperrors.ErrSessionNotFound) {
return false, nil
}
return false, fmt.Errorf("session existence check: %w", err)
}
return session != nil, nil
}
// buildGlobalSandboxConfig returns the process-wide *sandbox.Config that
// per-tenant overrides are merged onto.
func buildGlobalSandboxConfig() *sandbox.Config {
return sandbox.DeploymentConfig()
}
// newSandboxConfigDefaults exposes the deployment's inheritable sandbox
// defaults (secret-free) so the settings API can show what a workspace without
// its own overrides actually runs on.
func newSandboxConfigDefaults() *sandbox.ConfigDefaults {
return sandbox.DescribeDefaults(buildGlobalSandboxConfig())
}
// newTenantSandboxResolver wires the per-tenant resolver. The process-wide
// manager remains the fallback for tenants that configured nothing, so
// existing deployments are unaffected.
func newTenantSandboxResolver(
defaultManager sandbox.Manager,
loader sandbox.TenantSandboxConfigLoader,
redisClient *redis.Client,
sessionRepo interfaces.SessionRepository,
) sandbox.TenantSandboxResolver {
ctx := context.Background()
// Tenants may configure cube/e2b regardless of the global mode, so the
// resolver needs the same Redis-backed binding guarantees the global
// remote path demands. Without them per-tenant config stays disabled and
// every workspace keeps using the process-wide manager.
store, storeKind, err := selectSessionBindingStore(redisClient, true)
if err != nil {
logger.Warnf(ctx,
"Per-tenant sandbox config disabled: %v", err)
return nil
}
resolver, err := sandbox.NewTenantSandboxResolver(sandbox.TenantSandboxResolverDeps{
GlobalConfig: buildGlobalSandboxConfig(),
DefaultManager: defaultManager,
Loader: loader,
Store: store,
Checker: sessionExistenceCheckerFor(sessionRepo),
SharedTransport: sandbox.NewGuardedTransport(),
})
if err != nil {
logger.Warnf(ctx,
"Failed to initialize tenant sandbox resolver: %v "+
"(per-tenant sandbox config disabled)", err)
return nil
}
logger.Infof(ctx, "Tenant sandbox resolver configured: binding=%s", storeKind)
return resolver
}

View File

@ -0,0 +1,104 @@
package container
import (
"context"
"errors"
"strconv"
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
func TestSelectSessionBindingStorePrefersRedis(t *testing.T) {
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
t.Cleanup(func() { _ = client.Close() })
store, kind, err := selectSessionBindingStore(client, true)
require.NoError(t, err)
require.Equal(t, "redis", kind)
require.IsType(t, &sandbox.RedisSessionSandboxBindingStore{}, store)
}
func TestSelectSessionBindingStoreRequiresRedisForRemoteModes(t *testing.T) {
_, _, err := selectSessionBindingStore(nil, true)
require.Error(t, err)
require.Contains(t, err.Error(), "require Redis")
}
func TestSelectSessionBindingStoreAllowsMemoryWhenOptedIn(t *testing.T) {
t.Setenv("WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING", "true")
store, kind, err := selectSessionBindingStore(nil, true)
require.NoError(t, err)
require.Equal(t, "memory", kind)
require.IsType(t, &sandbox.MemorySessionSandboxBindingStore{}, store)
}
func TestSelectSessionBindingStoreFallsBackToMemoryWhenNotRequired(t *testing.T) {
store, kind, err := selectSessionBindingStore(nil, false)
require.NoError(t, err)
require.Equal(t, "memory", kind)
require.IsType(t, &sandbox.MemorySessionSandboxBindingStore{}, store)
}
// fakeSessionLookup implements the narrow sessionExistenceLookup surface the
// checker depends on. Keeping the surface narrow means the test double is a
// couple of lines instead of the full 16-method SessionRepository stub.
type fakeSessionLookup struct {
byID map[string]*types.Session
err error
}
func (f *fakeSessionLookup) GetByID(_ context.Context, tenantID uint64, id string) (*types.Session, error) {
if f.err != nil {
return nil, f.err
}
if s, ok := f.byID[id+"@"+strconv.FormatUint(tenantID, 10)]; ok {
return s, nil
}
return nil, gorm.ErrRecordNotFound
}
func TestSessionExistenceCheckerBackedByRepository(t *testing.T) {
repo := &fakeSessionLookup{
byID: map[string]*types.Session{
"session-a@42": {ID: "session-a", TenantID: 42},
},
}
checker := sessionExistenceCheckerFor(repo)
ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
require.NoError(t, err)
require.True(t, ok)
ok, err = checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "missing"})
require.NoError(t, err)
require.False(t, ok)
}
func TestSessionExistenceCheckerPropagatesTransientErrors(t *testing.T) {
fault := errors.New("database offline")
repo := &fakeSessionLookup{err: fault}
checker := sessionExistenceCheckerFor(repo)
ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
require.ErrorIs(t, err, fault)
require.False(t, ok)
}
func TestSessionExistenceCheckerFallsBackToPermissiveWhenLookupNil(t *testing.T) {
// Lite deployments (no database) still need to boot; a nil lookup
// hands us the permissive checker so the lifecycle coordinator never
// blocks resolution on a missing dependency.
checker := sessionExistenceCheckerFor(nil)
ok, err := checker.SessionExists(context.Background(), sandbox.SessionSandboxKey{TenantID: 42, SessionID: "session-a"})
require.NoError(t, err)
require.True(t, ok)
}

View File

@ -17,6 +17,13 @@ import (
"github.com/gin-gonic/gin"
)
// sandboxConfigLookup is the existence check an agent's sandbox selection needs.
// Narrower than the full config service so this handler cannot grow a dependency
// on config mutation.
type sandboxConfigLookup interface {
Get(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
}
// CustomAgentHandler defines the HTTP handler for custom agent operations
type CustomAgentHandler struct {
service interfaces.CustomAgentService
@ -25,6 +32,9 @@ type CustomAgentHandler struct {
// userService 仅用于 list 接口批量回填 creator_name,作用见
// KnowledgeBaseHandler.userService。
userService interfaces.UserService
// sandboxConfigs validates an agent's sandbox backend selection. Optional —
// nil in partially-wired unit tests, where the selection is left unchecked.
sandboxConfigs sandboxConfigLookup
}
// NewCustomAgentHandler creates a new custom agent handler instance
@ -33,12 +43,14 @@ func NewCustomAgentHandler(
imService *im.Service,
disabledRepo interfaces.TenantDisabledSharedAgentRepository,
userService interfaces.UserService,
sandboxConfigs *service.TenantSandboxConfigService,
) *CustomAgentHandler {
return &CustomAgentHandler{
service: service,
imService: imService,
disabledRepo: disabledRepo,
userService: userService,
service: service,
imService: imService,
disabledRepo: disabledRepo,
userService: userService,
sandboxConfigs: sandboxConfigs,
}
}
@ -86,6 +98,10 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
c.Error(err)
return
}
if err := h.validateAgentSandboxConfig(ctx, req.Config); err != nil {
c.Error(err)
return
}
// Build agent object
agent := &types.CustomAgent{
@ -329,6 +345,10 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
c.Error(err)
return
}
if err := h.validateAgentSandboxConfig(ctx, req.Config); err != nil {
c.Error(err)
return
}
// Build agent object
agent := &types.CustomAgent{
@ -646,6 +666,34 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
})
}
// validateAgentSandboxConfig rejects a selection the workspace does not have.
//
// Checking at save time is what makes the mistake fixable: a dangling reference
// only fails when the agent next runs a skill, mid-conversation, as an opaque
// resolution error with no hint about which agent to edit.
func (h *CustomAgentHandler) validateAgentSandboxConfig(
ctx context.Context, cfg types.CustomAgentConfig,
) error {
configID := strings.TrimSpace(cfg.SandboxConfigID)
if configID == "" || h.sandboxConfigs == nil {
// Empty means the deployment-wide default, which always exists.
return nil
}
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return errors.NewUnauthorizedError("Missing workspace context")
}
stored, err := h.sandboxConfigs.Get(ctx, tenantID, configID)
if err != nil {
return errors.NewInternalServerError("Failed to verify sandbox config").
WithDetails(err.Error())
}
if stored == nil {
return errors.NewBadRequestError("所选沙箱后端配置不存在,请重新选择")
}
return nil
}
func authorizeAgentKnowledgeScope(ctx context.Context, cfg types.CustomAgentConfig) error {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok || !scope.IsKnowledgeBaseRestricted() {

View File

@ -0,0 +1,117 @@
package handler
import (
"context"
"encoding/json"
stderrors "errors"
"net/http"
"testing"
"github.com/stretchr/testify/require"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
)
// stubSandboxConfigLookup answers the existence check without a database.
type stubSandboxConfigLookup struct {
entity *types.TenantSandboxConfigEntity
err error
lookups []string
}
func (s *stubSandboxConfigLookup) Get(
_ context.Context, _ uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
s.lookups = append(s.lookups, id)
return s.entity, s.err
}
func agentTenantContext() context.Context {
return context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
}
// The field must round-trip through the agent's JSON config column, since that
// is where it is persisted (no dedicated column).
func TestAgentConfigCarriesSandboxConfigID(t *testing.T) {
cfg := types.CustomAgentConfig{
AgentMode: "smart-reasoning",
SandboxConfigID: "cfg-a",
}
raw, err := json.Marshal(cfg)
require.NoError(t, err)
require.Contains(t, string(raw), `"sandbox_config_id":"cfg-a"`)
var back types.CustomAgentConfig
require.NoError(t, json.Unmarshal(raw, &back))
require.Equal(t, "cfg-a", back.SandboxConfigID)
}
// Empty must be omitted so existing agents keep an unchanged config payload.
func TestAgentConfigOmitsEmptySandboxConfigID(t *testing.T) {
raw, err := json.Marshal(types.CustomAgentConfig{AgentMode: "quick-answer"})
require.NoError(t, err)
require.NotContains(t, string(raw), "sandbox_config_id")
}
// Saving a dangling reference must fail here with a readable message. Deferring
// it means the agent looks fine until its first skill execution, which then dies
// on an opaque resolver error mid-conversation.
func TestAgentSandboxConfigValidationRejectsUnknownID(t *testing.T) {
lookup := &stubSandboxConfigLookup{}
h := &CustomAgentHandler{sandboxConfigs: lookup}
err := h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-gone"})
var appErr *apperrors.AppError
require.ErrorAs(t, err, &appErr)
require.Equal(t, http.StatusBadRequest, appErr.HTTPCode)
require.Equal(t, []string{"cfg-gone"}, lookup.lookups)
}
func TestAgentSandboxConfigValidationAcceptsExistingID(t *testing.T) {
lookup := &stubSandboxConfigLookup{
entity: &types.TenantSandboxConfigEntity{ID: "cfg-a", TenantID: 7},
}
h := &CustomAgentHandler{sandboxConfigs: lookup}
require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-a"}))
}
// Most agents run on the deployment default, so the common path must not pay for
// a lookup - and must never be rejected for leaving the field blank.
func TestAgentSandboxConfigValidationSkipsEmptyID(t *testing.T) {
lookup := &stubSandboxConfigLookup{}
h := &CustomAgentHandler{sandboxConfigs: lookup}
require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: " "}))
require.Empty(t, lookup.lookups)
}
// A lookup failure is not the admin's fault; it must not read as "you picked a
// config that does not exist".
func TestAgentSandboxConfigValidationSurfacesLookupFailure(t *testing.T) {
lookup := &stubSandboxConfigLookup{err: stderrors.New("database is on fire")}
h := &CustomAgentHandler{sandboxConfigs: lookup}
err := h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-a"})
var appErr *apperrors.AppError
require.ErrorAs(t, err, &appErr)
require.Equal(t, http.StatusInternalServerError, appErr.HTTPCode)
}
// Partially-wired handlers appear in tests and in deployments without the
// config service; they must not reject every agent that selects a backend.
func TestAgentSandboxConfigValidationSkipsWhenServiceMissing(t *testing.T) {
h := &CustomAgentHandler{}
require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-a"}))
}

View File

@ -0,0 +1,324 @@
package handler
import (
"context"
stderrors "errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// --- Sandbox connectivity check ---
// SandboxCheckRequest is the body for POST /system/sandbox-check. Secrets may
// arrive redacted; they are resolved against the workspace's stored config so
// an admin can test without retyping an API key.
type SandboxCheckRequest struct {
Config *types.TenantSandboxConfig `json:"config"`
// ConfigID lets an edit form test stored credentials while overriding only
// the fields the admin changed in the drawer.
ConfigID string `json:"config_id"`
// Deep additionally creates and destroys one sandbox, which is the only
// way to validate the template ID, Cube's proxy/envd data plane,
// in-sandbox execution, and outbound egress (CN + international probes,
// any one success). It consumes real sandbox time, so it is opt-in.
Deep bool `json:"deep"`
}
// SandboxCheckItem is one probe outcome. OK is nil when the probe was not
// executed, which distinguishes "skipped" from "failed" in the UI.
type SandboxCheckItem struct {
Name string `json:"name"`
OK *bool `json:"ok"`
Message string `json:"message,omitempty"`
LatencyMS int64 `json:"latency_ms,omitempty"`
}
// SandboxCheckResponse aggregates the probes for one sandbox configuration.
type SandboxCheckResponse struct {
OK bool `json:"ok"`
Provider string `json:"provider"`
Checks []SandboxCheckItem `json:"checks"`
Capabilities map[string]bool `json:"capabilities,omitempty"`
}
// add records an executed probe. A single failure fails the whole result.
func (r *SandboxCheckResponse) add(name string, ok bool, message string, latencyMS int64) {
value := ok
r.Checks = append(r.Checks, SandboxCheckItem{
Name: name, OK: &value, Message: message, LatencyMS: latencyMS,
})
if !ok {
r.OK = false
}
}
// skip records a probe that was not run; it never affects OK.
func (r *SandboxCheckResponse) skip(name, message string) {
r.Checks = append(r.Checks, SandboxCheckItem{Name: name, OK: nil, Message: message})
}
// CheckSandboxConfig tests a sandbox configuration without persisting it.
// @Summary 测试沙箱连通性
// @Description 使用当前填写的参数测试沙箱后端连通性,不保存配置;deep=true 会额外创建并销毁一个沙箱
// @Tags 系统
// @Accept json
// @Produce json
// @Param body body SandboxCheckRequest true "沙箱配置"
// @Success 200 {object} SandboxCheckResponse
// @Router /system/sandbox-check [post]
func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
var req SandboxCheckRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "请求体格式错误"})
return
}
tenant, _ := types.TenantInfoFromContext(c.Request.Context())
if tenant == nil {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "空间为空"})
return
}
var stored *types.TenantSandboxConfig
incoming := req.Config
if req.ConfigID != "" {
if h.sandboxConfigSvc == nil {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "沙箱配置服务不可用"})
return
}
entity, err := h.sandboxConfigSvc.Get(ctx, tenant.ID, req.ConfigID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})
return
}
if entity == nil {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "沙箱配置不存在"})
return
}
stored = entity.Config
if incoming == nil {
incoming = stored
}
}
merged, err := service.SanitizeSandboxConfig(incoming, stored)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})
return
}
effective, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DeploymentConfig())
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})
return
}
result := &SandboxCheckResponse{OK: true, Provider: string(effective.Type)}
client, err := sandbox.NewRemoteClientForCheck(effective)
if err != nil {
result.add("client_build", false, err.Error(), 0)
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
return
}
// Level 1: an authenticated control-plane call, which validates endpoint
// reachability AND credentials in a single round-trip.
start := time.Now()
healthErr := client.Health(ctx)
latency := time.Since(start).Milliseconds()
if healthErr != nil {
result.add("api_url_reachable", false, sandboxCheckReason(healthErr), latency)
result.skip("credential_valid", "未检测(控制面不可达)")
} else {
result.add("api_url_reachable", true, "", latency)
result.add("credential_valid", true, "", 0)
}
caps := client.Capabilities()
result.Capabilities = map[string]bool{
"supports_volumes": caps.SupportsVolumes,
"supports_pause_resume": caps.SupportsPauseResume,
"supports_reconnect": caps.SupportsReconnect,
}
if !req.Deep || healthErr != nil {
result.skip("template_exists", "未检测(需完整验证)")
result.skip("sandbox_exec", "未检测(需完整验证)")
result.skip("egress_available", "未检测(需完整验证)")
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
return
}
h.runDeepSandboxCheck(ctx, client, effective, result)
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
// runDeepSandboxCheck creates one throwaway sandbox and verifies a command can
// run inside it. The sandbox is always deleted, including on failure.
func (h *SystemHandler) runDeepSandboxCheck(
ctx context.Context,
client sandbox.RemoteSandboxClient,
cfg *sandbox.Config,
result *SandboxCheckResponse,
) {
probeCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
handle, err := client.Create(probeCtx, sandbox.RemoteCreateRequest{
TemplateID: sandbox.EffectiveTemplateID(cfg),
Timeout: sandbox.RemoteTimeoutPolicy{
Mode: sandbox.RemoteTimeoutExplicit,
Value: 2 * time.Minute,
Action: sandbox.RemoteOnTimeoutKill,
},
})
if err != nil {
result.add("template_exists", false, sandboxCheckReason(err), 0)
result.skip("sandbox_exec", "未检测(沙箱未创建)")
result.skip("egress_available", "未检测(沙箱未创建)")
return
}
defer func() {
// Detach from ctx so cleanup still runs if the request was cancelled;
// a leaked probe sandbox would otherwise sit there billing.
cleanupCtx, cleanupCancel := context.WithTimeout(
context.WithoutCancel(ctx), 30*time.Second)
defer cleanupCancel()
if err := client.Delete(cleanupCtx, handle.ID()); err != nil {
logger.Warnf(ctx, "[SandboxCheck] failed to delete probe sandbox %s: %v",
handle.ID(), err)
}
}()
result.add("template_exists", true, "", 0)
const marker = "weknora-ok"
start := time.Now()
execResult, err := client.Exec(probeCtx, handle, sandbox.RemoteExecRequest{
Command: "echo",
Args: []string{marker},
User: sandbox.DefaultSandboxExecUser,
Timeout: 30 * time.Second,
})
latency := time.Since(start).Milliseconds()
switch {
case err != nil:
result.add("sandbox_exec", false, sandboxCheckReason(err), latency)
result.skip("egress_available", "未检测(沙箱执行失败)")
return
case execResult == nil || !strings.Contains(execResult.Stdout, marker):
result.add("sandbox_exec", false, "命令输出与预期不符", latency)
result.skip("egress_available", "未检测(沙箱执行失败)")
return
default:
result.add("sandbox_exec", true, "", latency)
}
h.probeSandboxEgress(probeCtx, client, handle, result)
}
// egressProbeTargets are tried in order; the first reachable one passes
// egress_available. Domestic and international endpoints cover regional
// egress policies without requiring both to succeed.
var egressProbeTargets = []struct {
label string
url string
}{
{label: "cn:baidu", url: "https://www.baidu.com"},
{label: "intl:1.1.1.1", url: "https://1.1.1.1"},
}
// probeSandboxEgress verifies the sandbox can reach the public internet.
// Any single target succeeding is enough — skill installs only need some
// outbound path, not both CN and international reachability.
func (h *SystemHandler) probeSandboxEgress(
ctx context.Context,
client sandbox.RemoteSandboxClient,
handle sandbox.RemoteSandboxHandle,
result *SandboxCheckResponse,
) {
// Echo which target succeeded so the UI message is actionable when
// only one region is reachable. First success exits 0 immediately.
var b strings.Builder
for _, target := range egressProbeTargets {
fmt.Fprintf(&b,
`if curl -fsS -o /dev/null -m 8 -I %s; then echo %s; exit 0; fi; `,
shellSingleQuote(target.url), shellSingleQuote(target.label))
}
b.WriteString(`echo "all probes failed" >&2; exit 1`)
start := time.Now()
execResult, err := client.Exec(ctx, handle, sandbox.RemoteExecRequest{
Command: b.String(),
Shell: true,
User: sandbox.DefaultSandboxExecUser,
Timeout: 30 * time.Second,
})
latency := time.Since(start).Milliseconds()
switch {
case err != nil:
result.add("egress_available", false, sandboxCheckReason(err), latency)
case execResult == nil:
result.add("egress_available", false, "出网探测无返回", latency)
case execResult.Killed:
result.add("egress_available", false, "出网探测超时", latency)
case execResult.ExitCode != 0:
msg := strings.TrimSpace(execResult.Stderr)
if msg == "" {
msg = strings.TrimSpace(execResult.Stdout)
}
if msg == "" {
msg = "国内与国际探测目标均不可达"
}
result.add("egress_available", false, msg, latency)
default:
hit := strings.TrimSpace(execResult.Stdout)
if hit == "" {
hit = "ok"
}
result.add("egress_available", true, "reachable via "+hit, latency)
}
}
// shellSingleQuote wraps s for safe inclusion in a single-quoted shell string.
func shellSingleQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// sandboxCheckReason turns a provider error into a readable cause using the
// adapter's normalized RemoteError.Kind, so the UI never shows raw SDK text.
func sandboxCheckReason(err error) string {
if err == nil {
return ""
}
var remoteErr *sandbox.RemoteError
if !stderrors.As(err, &remoteErr) {
return err.Error()
}
switch remoteErr.Kind {
case sandbox.RemoteErrorKindAuthentication:
return "认证失败:API Key 无效或无权限"
case sandbox.RemoteErrorKindNotFound:
return "资源不存在:请检查模板 ID"
case sandbox.RemoteErrorKindTimeout:
return "请求超时:端点不可达或响应过慢"
case sandbox.RemoteErrorKindUnavailable:
return "服务不可用:端点拒绝连接"
case sandbox.RemoteErrorKindCapacity:
return "配额不足或触发限流"
case sandbox.RemoteErrorKindUnsupported:
return "该后端不支持此操作"
case sandbox.RemoteErrorKindInvalidRequest:
return "参数无效:" + remoteErr.Message
default:
return remoteErr.Message
}
}

View File

@ -0,0 +1,341 @@
package handler
import (
"context"
stderrors "errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
type sandboxConfigService interface {
Create(context.Context, uint64, service.CreateSandboxConfigInput) (*types.TenantSandboxConfigEntity, error)
List(context.Context, uint64) ([]*types.TenantSandboxConfigEntity, error)
Get(context.Context, uint64, string) (*types.TenantSandboxConfigEntity, error)
Update(context.Context, uint64, string, service.UpdateSandboxConfigInput) (*types.TenantSandboxConfigEntity, error)
Delete(context.Context, uint64, string, bool) error
Inventory(context.Context, uint64, string) (service.SandboxInventory, error)
WorkspaceScriptsDisabled(context.Context, uint64) (bool, error)
SetWorkspaceScriptsDisabled(context.Context, uint64, bool) error
}
type SandboxConfigHandler struct {
service sandboxConfigService
defaults *sandbox.ConfigDefaults
}
func NewSandboxConfigHandler(
service *service.TenantSandboxConfigService,
defaults *sandbox.ConfigDefaults,
) *SandboxConfigHandler {
return &SandboxConfigHandler{service: service, defaults: defaults}
}
type sandboxConfigRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description,omitempty"`
Config *types.TenantSandboxConfig `json:"config"`
}
// sandboxConfigResponse is the only outward projection of stored configs, so a
// new read path cannot accidentally return decrypted credentials.
type sandboxConfigResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
SandboxType string `json:"sandbox_type"`
Config *types.TenantSandboxConfig `json:"config"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func sandboxConfigTenantID(c *gin.Context) uint64 {
return c.GetUint64(types.TenantIDContextKey.String())
}
func toSandboxConfigResponse(e *types.TenantSandboxConfigEntity) sandboxConfigResponse {
if e == nil {
return sandboxConfigResponse{}
}
return sandboxConfigResponse{
ID: e.ID,
Name: e.Name,
Description: e.Description,
SandboxType: e.SandboxType,
Config: types.SandboxConfigForResponse(e.Config, true),
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
}
}
// respondSandboxesStillLive carries the exact inventory that refused the write;
// recomputing it could race and show the admin a different reason.
func respondSandboxesStillLive(c *gin.Context, inv service.SandboxInventory) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": gin.H{
"code": "sandboxes_still_live",
"message": "该配置仍有运行中或已暂停的沙箱,请先结束或删除相关会话,或新建一份配置",
"data": inv,
},
})
}
func respondSandboxInventoryUnverifiable(c *gin.Context) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": gin.H{
"code": "sandbox_inventory_unverifiable",
"message": "无法连接该后端核实是否仍有沙箱",
},
})
}
func respondSandboxConfigCordoned(c *gin.Context) {
c.JSON(http.StatusLocked, gin.H{
"success": false,
"error": gin.H{
"code": "sandbox_config_cordoned",
"message": "该配置正在被其他人修改,请稍后重试",
},
})
}
func respondSandboxConfigRefusal(c *gin.Context, err error) bool {
var liveErr *service.SandboxesStillLiveError
if stderrors.As(err, &liveErr) {
respondSandboxesStillLive(c, liveErr.Inventory)
return true
}
if stderrors.Is(err, service.ErrSandboxInventoryUnverifiable) {
respondSandboxInventoryUnverifiable(c)
return true
}
if stderrors.Is(err, repository.ErrSandboxConfigCordoned) {
respondSandboxConfigCordoned(c)
return true
}
return false
}
// respondSandboxConfigServiceError promotes the service's input-validation
// sentinels to 400. They are matched as sentinels rather than by message so a
// reworded error cannot silently start returning 500 for bad input.
func respondSandboxConfigServiceError(c *gin.Context, err error) {
switch {
case stderrors.Is(err, service.ErrSandboxConfigNameRequired),
stderrors.Is(err, service.ErrNamedSandboxBackendUnsupported),
stderrors.Is(err, sandbox.ErrUnsupportedSandboxType),
stderrors.Is(err, sandbox.ErrUnsafeOutboundURL),
stderrors.Is(err, sandbox.ErrSandboxConfigIncomplete):
c.Error(apperrors.NewBadRequestError(err.Error()))
default:
c.Error(err)
}
}
// List godoc
// @Summary List sandbox configs
// @Description List workspace sandbox backend configs with credentials masked and deployment defaults included.
// @Tags SandboxConfig
// @Produce json
// @Success 200 {object} map[string]interface{} "Sandbox configs and defaults"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs [get]
func (h *SandboxConfigHandler) List(c *gin.Context) {
ctx := c.Request.Context()
tenantID := sandboxConfigTenantID(c)
configs, err := h.service.List(ctx, tenantID)
if err != nil {
c.Error(err)
return
}
disabled, err := h.service.WorkspaceScriptsDisabled(ctx, tenantID)
if err != nil {
c.Error(err)
return
}
data := make([]sandboxConfigResponse, 0, len(configs))
for _, cfg := range configs {
data = append(data, toSandboxConfigResponse(cfg))
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": data,
"defaults": h.defaults,
"workspace_scripts_disabled": disabled,
})
}
type workspacePolicyRequest struct {
ScriptsDisabled bool `json:"scripts_disabled"`
}
// SetWorkspacePolicy toggles script execution for agents that use the deployment default.
func (h *SandboxConfigHandler) SetWorkspacePolicy(c *gin.Context) {
var req workspacePolicyRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
tenantID := sandboxConfigTenantID(c)
if err := h.service.SetWorkspaceScriptsDisabled(c.Request.Context(), tenantID, req.ScriptsDisabled); err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "workspace_scripts_disabled": req.ScriptsDisabled})
}
// Create godoc
// @Summary Create sandbox config
// @Description Create a named workspace sandbox backend config. Credentials are masked in the response.
// @Tags SandboxConfig
// @Accept json
// @Produce json
// @Param request body sandboxConfigRequest true "Sandbox backend config"
// @Success 201 {object} map[string]interface{} "Created sandbox config"
// @Failure 400 {object} apperrors.AppError "Invalid request or validation failure"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs [post]
func (h *SandboxConfigHandler) Create(c *gin.Context) {
var req sandboxConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
created, err := h.service.Create(c.Request.Context(), sandboxConfigTenantID(c),
service.CreateSandboxConfigInput{
Name: req.Name,
Description: req.Description,
Config: req.Config,
})
if err != nil {
respondSandboxConfigServiceError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{"success": true, "data": toSandboxConfigResponse(created)})
}
// Get godoc
// @Summary Get sandbox config
// @Description Retrieve a workspace sandbox backend config with credentials masked.
// @Tags SandboxConfig
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Success 200 {object} map[string]interface{} "Sandbox config"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Sandbox config not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id} [get]
func (h *SandboxConfigHandler) Get(c *gin.Context) {
cfg, err := h.service.Get(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"))
if err != nil {
c.Error(err)
return
}
if cfg == nil {
c.Error(apperrors.NewNotFoundError("sandbox config not found"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": toSandboxConfigResponse(cfg)})
}
// Update godoc
// @Summary Update sandbox config
// @Description Update a sandbox backend config. Identity-field changes are refused while the config owns live or paused sandboxes.
// @Tags SandboxConfig
// @Accept json
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Param request body sandboxConfigRequest true "Updated sandbox config"
// @Success 200 {object} map[string]interface{} "Updated sandbox config"
// @Failure 400 {object} apperrors.AppError "Invalid request or validation failure"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Sandbox config not found"
// @Failure 409 {object} map[string]interface{} "Live sandboxes or unverifiable inventory"
// @Failure 423 {object} map[string]interface{} "Sandbox config is being modified by another request"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id} [put]
func (h *SandboxConfigHandler) Update(c *gin.Context) {
var req sandboxConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
updated, err := h.service.Update(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"),
service.UpdateSandboxConfigInput{
Name: req.Name,
Description: req.Description,
Config: req.Config,
})
if err != nil {
if respondSandboxConfigRefusal(c, err) {
return
}
respondSandboxConfigServiceError(c, err)
return
}
if updated == nil {
c.Error(apperrors.NewNotFoundError("sandbox config not found"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": toSandboxConfigResponse(updated)})
}
// Delete godoc
// @Summary Delete sandbox config
// @Description Soft-delete a sandbox backend config. force=true only overrides unverifiable provider inventory, never confirmed live sandboxes.
// @Tags SandboxConfig
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Param force query bool false "Force delete when inventory is unverifiable"
// @Success 200 {object} map[string]interface{} "Deletion success"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 409 {object} map[string]interface{} "Live sandboxes or unverifiable inventory"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id} [delete]
func (h *SandboxConfigHandler) Delete(c *gin.Context) {
force := c.Query("force") == "true"
if err := h.service.Delete(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), force); err != nil {
if respondSandboxConfigRefusal(c, err) {
return
}
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// Inventory godoc
// @Summary Inspect sandbox config inventory
// @Description Return live/paused sandbox inventory and affected agent names for one config.
// @Tags SandboxConfig
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Success 200 {object} map[string]interface{} "Sandbox inventory"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/sandboxes [get]
func (h *SandboxConfigHandler) Inventory(c *gin.Context) {
inv, err := h.service.Inventory(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"))
if err != nil {
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": inv})
}

View File

@ -0,0 +1,249 @@
package handler
import (
"context"
"encoding/json"
stderrors "errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/application/service"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// Responses must never carry plaintext credentials, no matter which path
// produced them.
func TestSandboxConfigResponseMasksSecrets(t *testing.T) {
cfg := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "super-secret"},
EnvVars: map[string]string{"TOKEN": "also-secret"},
}
entity := &types.TenantSandboxConfigEntity{
ID: "cfg-a",
Name: "primary",
SandboxType: "e2b",
Config: cfg,
CreatedAt: time.Unix(1, 0),
UpdatedAt: time.Unix(2, 0),
}
body, err := json.Marshal(toSandboxConfigResponse(entity))
require.NoError(t, err)
require.NotContains(t, string(body), "super-secret")
require.NotContains(t, string(body), "also-secret")
require.Contains(t, string(body), types.RedactedSecretPlaceholder)
}
// The 409 must be machine-readable: the UI renders "release N sandboxes first"
// from it rather than parsing a message string.
func TestSandboxesStillLiveMapsTo409WithCounts(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.PUT("/sandbox-configs/:id", func(c *gin.Context) {
respondSandboxesStillLive(c, service.SandboxInventory{
SandboxCount: 3,
SessionIDs: []string{"s-1", "s-2"},
AgentNames: []string{"数据分析"},
})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPut, "/sandbox-configs/cfg-a",
strings.NewReader(`{}`))
router.ServeHTTP(w, req)
require.Equal(t, http.StatusConflict, w.Code)
var payload struct {
Error struct {
Code string `json:"code"`
Data struct {
SandboxCount int `json:"sandbox_count"`
SessionIDs []string `json:"session_ids"`
AgentNames []string `json:"agent_names"`
} `json:"data"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
require.Equal(t, "sandboxes_still_live", payload.Error.Code)
require.Equal(t, 3, payload.Error.Data.SandboxCount)
require.Len(t, payload.Error.Data.SessionIDs, 2)
require.Equal(t, []string{"数据分析"}, payload.Error.Data.AgentNames)
}
func TestSandboxInventoryUnverifiableMapsToDistinct409(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.DELETE("/sandbox-configs/:id", func(c *gin.Context) {
respondSandboxInventoryUnverifiable(c)
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-a", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusConflict, w.Code)
var payload struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
require.Equal(t, "sandbox_inventory_unverifiable", payload.Error.Code)
require.Contains(t, payload.Error.Message, "无法连接")
}
func TestSandboxConfigDeletePassesForceQuery(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &fakeSandboxConfigService{}
h := &SandboxConfigHandler{service: svc, defaults: &sandbox.ConfigDefaults{}}
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(42))
c.Next()
})
router.DELETE("/sandbox-configs/:id", h.Delete)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-a?force=true", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, uint64(42), svc.deleteTenantID)
require.Equal(t, "cfg-a", svc.deleteID)
require.True(t, svc.deleteForce)
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-b", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "cfg-b", svc.deleteID)
require.False(t, svc.deleteForce)
}
// Bad input must not surface as a 500. The sentinels are matched with errors.Is
// so rewording a message cannot silently reclassify these.
func TestSandboxConfigValidationSentinelsMapTo400(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name string
err error
}{
{"missing name", service.ErrSandboxConfigNameRequired},
{"named backend unsupported", service.ErrNamedSandboxBackendUnsupported},
{"unknown backend", fmt.Errorf("%w %q", sandbox.ErrUnsupportedSandboxType, "quantum")},
{"unsafe endpoint", fmt.Errorf("%w: host is private", sandbox.ErrUnsafeOutboundURL)},
} {
t.Run(tc.name, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
respondSandboxConfigServiceError(c, tc.err)
require.Len(t, c.Errors, 1)
var appErr *apperrors.AppError
require.ErrorAs(t, c.Errors[0].Err, &appErr)
require.Equal(t, http.StatusBadRequest, appErr.HTTPCode)
})
}
}
// An unexpected failure must keep its original error so the middleware can map
// it, rather than being flattened into a 400.
func TestSandboxConfigUnexpectedErrorIsNotDowngraded(t *testing.T) {
gin.SetMode(gin.TestMode)
boom := stderrors.New("database is on fire")
c, _ := gin.CreateTestContext(httptest.NewRecorder())
respondSandboxConfigServiceError(c, boom)
require.Len(t, c.Errors, 1)
require.ErrorIs(t, c.Errors[0].Err, boom)
}
type fakeSandboxConfigService struct {
deleteTenantID uint64
deleteID string
deleteForce bool
}
func (s *fakeSandboxConfigService) Create(
context.Context,
uint64,
service.CreateSandboxConfigInput,
) (*types.TenantSandboxConfigEntity, error) {
return nil, nil
}
func (s *fakeSandboxConfigService) List(
context.Context,
uint64,
) ([]*types.TenantSandboxConfigEntity, error) {
return nil, nil
}
func (s *fakeSandboxConfigService) Get(
context.Context,
uint64,
string,
) (*types.TenantSandboxConfigEntity, error) {
return nil, nil
}
func (s *fakeSandboxConfigService) Update(
context.Context,
uint64,
string,
service.UpdateSandboxConfigInput,
) (*types.TenantSandboxConfigEntity, error) {
return nil, nil
}
func (s *fakeSandboxConfigService) Delete(
_ context.Context,
tenantID uint64,
id string,
force bool,
) error {
s.deleteTenantID = tenantID
s.deleteID = id
s.deleteForce = force
return nil
}
func (s *fakeSandboxConfigService) Inventory(
context.Context,
uint64,
string,
) (service.SandboxInventory, error) {
return service.SandboxInventory{}, nil
}
func (s *fakeSandboxConfigService) WorkspaceScriptsDisabled(
context.Context,
uint64,
) (bool, error) {
return false, nil
}
func (s *fakeSandboxConfigService) SetWorkspaceScriptsDisabled(
context.Context,
uint64,
bool,
) error {
return nil
}

View File

@ -8,7 +8,9 @@ import (
"sync"
"time"
"github.com/Tencent/WeKnora/internal/agent/skills"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@ -21,6 +23,7 @@ import (
type AgentStreamHandler struct {
ctx context.Context
sessionID string
tenantID uint64 // Tenant that owns this session; used when persisting skill artifacts.
assistantMessageID string
requestID string
receivedAt time.Time // Handler entry timestamp, used for TTFB logging
@ -30,6 +33,11 @@ type AgentStreamHandler struct {
eventBus *event.EventBus
// artifactCollector drains skill-generated files from the session
// sandbox after the agent completes. Nil when the sandbox backend
// doesn't support artifact collection or WeKnora was built without it.
artifactCollector *service.ArtifactCollector
// State tracking
knowledgeRefs []*types.SearchResult
finalAnswer string
@ -76,20 +84,24 @@ func (h *AgentStreamHandler) composeFinalAnswer() string {
func NewAgentStreamHandler(
ctx context.Context,
sessionID, assistantMessageID, requestID string,
tenantID uint64,
receivedAt time.Time,
assistantMessage *types.Message,
streamManager interfaces.StreamManager,
eventBus *event.EventBus,
artifactCollector *service.ArtifactCollector,
) *AgentStreamHandler {
return &AgentStreamHandler{
ctx: ctx,
sessionID: sessionID,
tenantID: tenantID,
assistantMessageID: assistantMessageID,
requestID: requestID,
receivedAt: receivedAt,
assistantMessage: assistantMessage,
streamManager: streamManager,
eventBus: eventBus,
artifactCollector: artifactCollector,
knowledgeRefs: make([]*types.SearchResult, 0),
eventStartTimes: make(map[string]time.Time),
}
@ -603,6 +615,34 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
h.assistantMessage.AgentSteps = agenttools.SanitizeAgentStepsForStorage(steps)
}
}
// Drain skill-generated files from the sandbox into persistent
// storage. Best-effort: any failure is logged and the turn is
// persisted without artifacts. Collect is a no-op when either the
// collector wasn't wired in, no sandbox is bound, or no files were
// produced — those cases must not disturb the completion path.
if h.artifactCollector != nil {
collectCtx := context.WithoutCancel(h.ctx)
artifacts, err := h.artifactCollector.Collect(
collectCtx,
h.sessionID,
h.assistantMessageID,
h.tenantID,
skills.ArtifactOutputDir(),
)
if err != nil {
logger.GetLogger(h.ctx).Warnf(
"artifact collect failed session=%s message=%s: %v",
h.sessionID, h.assistantMessageID, err,
)
} else if len(artifacts) > 0 {
h.assistantMessage.Artifacts = artifacts
logger.GetLogger(h.ctx).Infof(
"artifact collect attached %d file(s) to message=%s session=%s",
len(artifacts), h.assistantMessageID, h.sessionID,
)
}
}
}
// Fallback: if no answer events were streamed but we have a final answer,
@ -646,19 +686,49 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
}
// Send completion event to stream manager so SSE can detect completion
completeData := map[string]interface{}{
"total_steps": data.TotalSteps,
"total_duration_ms": data.TotalDurationMs,
}
// Attach the freshly-collected artifacts so the frontend can render the
// download button without waiting for a page refresh. We strip the
// storage URL and any other server-only fields via publicArtifactViews
// — clients only ever download through /artifacts/:index which enforces
// tenant ownership.
if len(h.assistantMessage.Artifacts) > 0 {
completeData["artifacts"] = publicArtifactViews(h.assistantMessage.Artifacts)
}
if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeComplete,
Content: "",
Done: true,
Timestamp: time.Now(),
Data: map[string]interface{}{
"total_steps": data.TotalSteps,
"total_duration_ms": data.TotalDurationMs,
},
Data: completeData,
}); err != nil {
logger.GetLogger(h.ctx).Errorf("Append complete event to stream failed: %v", err)
}
return nil
}
// publicArtifactViews returns a redacted view of the artifact list suitable
// for direct serialization onto the SSE stream. The storage URL and any
// other server-only fields are stripped; the frontend uses (index, name,
// size, source_path, mod_time, created_at) to render the download drawer
// and calls /artifacts/:index/download to fetch the bytes.
func publicArtifactViews(list types.MessageArtifacts) []map[string]interface{} {
out := make([]map[string]interface{}, 0, len(list))
for i, a := range list {
out = append(out, map[string]interface{}{
"index": i,
"file_name": a.FileName,
"file_type": a.FileType,
"file_size": a.FileSize,
"source_path": a.SourcePath,
"mod_time": a.ModTime,
"created_at": a.CreatedAt,
})
}
return out
}

View File

@ -0,0 +1,310 @@
package session
import (
stderrors "errors"
"io"
"mime"
"net/http"
"path/filepath"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
)
// paramSessionID resolves the session-id URL parameter regardless of which
// wildcard name the current route uses. GET-tree routes bind :id (to align
// with /sessions/:id), while POST-tree routes typically bind :session_id.
// Handlers call this helper instead of hard-coding one name so the same
// function serves both trees.
func paramSessionID(c *gin.Context) string {
if v := c.Param("session_id"); v != "" {
return v
}
return c.Param("id")
}
// ListSessionArtifacts godoc
// @Summary 列出会话生成的产物文件
// @Description 返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)
// @Tags 会话
// @Produce json
// @Param session_id path string true "会话ID"
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /sessions/{session_id}/artifacts [get]
//
// The endpoint powers the drawer that lists every file generated in the
// session; it does NOT return the storage URL (only names/sizes/mtimes), so
// clients cannot reach around the download endpoint by reading a
// provider:// path from the API response.
func (h *Handler) ListSessionArtifacts(c *gin.Context) {
ctx := c.Request.Context()
sessionID := secutils.SanitizeForLog(paramSessionID(c))
if sessionID == "" {
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Ownership + tenant check: GetSession enforces both. Returning 404 for
// unknown / non-owned sessions matches the rest of the session routes.
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
artifacts, err := h.messageService.GetSessionArtifacts(ctx, sessionID)
if err != nil {
logger.Errorf(ctx, "list session artifacts failed: session=%s err=%v", sessionID, err)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Strip the storage URL before serialising to the client; the URL is a
// server-side implementation detail (provider:// path) that must never
// escape the process. The client references artifacts by index in the
// download URL instead.
items := make([]artifactListItem, 0, len(artifacts))
for i, a := range artifacts {
items = append(items, artifactListItem{
Index: i,
FileName: a.FileName,
FileType: a.FileType,
FileSize: a.FileSize,
SourcePath: a.SourcePath,
ModTime: a.ModTime,
CreatedAt: a.CreatedAt,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": items,
})
}
// ListMessageArtifacts returns just the artifacts attached to a single
// assistant message. Used by the "download files from this reply" button on
// each bot message.
//
// Same-tenant/same-owner check flows through h.sessionService.GetSession
// exactly like ListSessionArtifacts.
//
// @Router /sessions/{session_id}/messages/{message_id}/artifacts [get]
func (h *Handler) ListMessageArtifacts(c *gin.Context) {
ctx := c.Request.Context()
sessionID := secutils.SanitizeForLog(paramSessionID(c))
messageID := secutils.SanitizeForLog(c.Param("message_id"))
if sessionID == "" || messageID == "" {
c.Error(errors.NewBadRequestError("session_id and message_id are required"))
return
}
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
msg, err := h.messageService.GetMessage(ctx, sessionID, messageID)
if err != nil || msg == nil {
c.Error(errors.NewNotFoundError("message not found"))
return
}
items := make([]artifactListItem, 0, len(msg.Artifacts))
for i, a := range msg.Artifacts {
items = append(items, artifactListItem{
Index: i,
FileName: a.FileName,
FileType: a.FileType,
FileSize: a.FileSize,
SourcePath: a.SourcePath,
ModTime: a.ModTime,
CreatedAt: a.CreatedAt,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": items,
})
}
// DownloadMessageArtifact streams a single skill-generated file to the
// client. Clients reference the artifact by its position (:index) in the
// assistant message's Artifacts array; the storage URL never leaves the
// server so callers cannot pivot to arbitrary blobs.
//
// @Router /sessions/{session_id}/messages/{message_id}/artifacts/{index}/download [get]
func (h *Handler) DownloadMessageArtifact(c *gin.Context) {
ctx := c.Request.Context()
sessionID := secutils.SanitizeForLog(paramSessionID(c))
messageID := secutils.SanitizeForLog(c.Param("message_id"))
indexParam := c.Param("index")
if sessionID == "" || messageID == "" || indexParam == "" {
c.Error(errors.NewBadRequestError("session_id, message_id and index are required"))
return
}
index, err := strconv.Atoi(indexParam)
if err != nil || index < 0 {
c.Error(errors.NewBadRequestError("invalid artifact index"))
return
}
// Ownership check: GetSession returns ErrSessionNotFound when the
// session doesn't belong to the calling tenant/user, so a 404 covers
// both "not found" and "forbidden" without leaking existence.
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
msg, err := h.messageService.GetMessage(ctx, sessionID, messageID)
if err != nil || msg == nil {
c.Error(errors.NewNotFoundError("message not found"))
return
}
if index >= len(msg.Artifacts) {
c.Error(errors.NewNotFoundError("artifact index out of range"))
return
}
artifact := msg.Artifacts[index]
if artifact.URL == "" {
c.Error(errors.NewNotFoundError("artifact storage path missing"))
return
}
if h.fileService == nil {
c.Error(errors.NewInternalServerError("file service unavailable"))
return
}
reader, err := h.fileService.GetFile(ctx, artifact.URL)
if err != nil {
logger.Warnf(ctx, "artifact download read failed: session=%s message=%s idx=%d err=%v",
sessionID, messageID, index, err)
c.Error(errors.NewNotFoundError("artifact blob missing"))
return
}
defer reader.Close()
// Force download semantics — artifacts are never rendered inline, matching
// the /files endpoint's active-content protection.
c.Header("Content-Type", mimeTypeFor(artifact.FileName))
c.Header("X-Content-Type-Options", "nosniff")
c.Header("Content-Disposition", buildAttachmentHeader(artifact.FileName))
if artifact.FileSize > 0 {
c.Header("Content-Length", strconv.FormatInt(artifact.FileSize, 10))
}
c.Status(http.StatusOK)
if _, err := io.Copy(c.Writer, reader); err != nil {
logger.Warnf(ctx, "artifact download stream failed: session=%s message=%s idx=%d err=%v",
sessionID, messageID, index, err)
}
}
// artifactListItem is the JSON shape returned by ListSessionArtifacts /
// ListMessageArtifacts. It intentionally omits the URL: clients reference
// each artifact through its position in the parent message's Artifacts
// array so the storage path never leaves the server.
type artifactListItem struct {
Index int `json:"index"`
FileName string `json:"file_name"`
FileType string `json:"file_type"`
FileSize int64 `json:"file_size"`
SourcePath string `json:"source_path"`
// time-typed fields serialise as RFC3339 strings — same convention as
// the rest of the messages API.
ModTime any `json:"mod_time"`
CreatedAt any `json:"created_at"`
}
// mimeTypeFor picks a Content-Type by extension and falls back to
// application/octet-stream so unknown types force a download prompt rather
// than being sniffed. Kept private to this file — the /files route has a
// stricter version with an SVG-neutralising branch; we don't need that here
// because Content-Disposition already blocks inline rendering.
func mimeTypeFor(name string) string {
ext := strings.ToLower(filepath.Ext(name))
if ext == "" {
return "application/octet-stream"
}
if ct := mime.TypeByExtension(ext); ct != "" {
return ct
}
return "application/octet-stream"
}
// buildAttachmentHeader returns a Content-Disposition value that preserves
// non-ASCII filenames (RFC 5987) while providing a safe fallback for
// ASCII-only clients.
func buildAttachmentHeader(name string) string {
// Strip control characters + quotes; keep the human-readable name.
ascii := strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f {
return -1
}
if r == '"' || r == '\\' {
return '_'
}
if r > 0x7e {
return -1
}
return r
}, name)
if ascii == "" {
ascii = "download"
}
encoded := (&urlPathEscaper{}).escape(name)
return "attachment; filename=\"" + ascii + "\"; filename*=UTF-8''" + encoded
}
// urlPathEscaper is a minimal RFC 3986 percent-encoder for the subset of
// bytes allowed in a filename*= value. We inline it to avoid importing
// net/url just for a two-line call, and because url.PathEscape encodes
// spaces as "+" (form-encoding) which HTTP clients then decode as literal
// "+" characters in the filename.
type urlPathEscaper struct{}
// escape percent-encodes every byte outside the "attr-char" grammar of RFC 5987.
// See https://datatracker.ietf.org/doc/html/rfc5987#section-3.2.1
func (urlPathEscaper) escape(s string) string {
var b strings.Builder
b.Grow(len(s))
const hex = "0123456789ABCDEF"
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case (c >= 'A' && c <= 'Z'), (c >= 'a' && c <= 'z'), (c >= '0' && c <= '9'):
b.WriteByte(c)
case c == '-' || c == '.' || c == '_' || c == '~':
b.WriteByte(c)
default:
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&0x0f])
}
}
return b.String()
}
// ensureAssistantOwnsArtifact is a small helper reserved for future
// authorisation refinements (per-message role checks). It is unused today
// but kept close to the handlers so future changes stay obvious.
var _ = types.MessageArtifact{}

View File

@ -0,0 +1,271 @@
package session
import (
"context"
stderrors "errors"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// -----------------------------------------------------------------------------
// Test doubles
//
// The download handler only touches three collaborators: SessionService (for
// ownership check), MessageService (for the message + artifact list), and
// FileService (for the blob stream). We embed the full interfaces so the
// zero-value struct compiles, then override just the methods each test
// exercises. A stray call to an un-stubbed method deliberately nil-panics
// so the failure surfaces immediately.
// -----------------------------------------------------------------------------
type stubSessionServiceForArtifacts struct {
interfaces.SessionService
getSession func(ctx context.Context, id string) (*types.Session, error)
}
func (s *stubSessionServiceForArtifacts) GetSession(ctx context.Context, id string) (*types.Session, error) {
return s.getSession(ctx, id)
}
type stubMessageServiceForArtifacts struct {
interfaces.MessageService
getMessage func(ctx context.Context, sessionID, id string) (*types.Message, error)
getSessionArtifact func(ctx context.Context, sessionID string) (types.MessageArtifacts, error)
}
func (s *stubMessageServiceForArtifacts) GetMessage(ctx context.Context, sessionID, id string) (*types.Message, error) {
return s.getMessage(ctx, sessionID, id)
}
func (s *stubMessageServiceForArtifacts) GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error) {
if s.getSessionArtifact == nil {
return types.MessageArtifacts{}, nil
}
return s.getSessionArtifact(ctx, sessionID)
}
// fakeArtifactFileService serves canned bytes for a single URL.
type fakeArtifactFileService struct {
interfaces.FileService
url string
data []byte
}
func (f *fakeArtifactFileService) GetFile(_ context.Context, url string) (io.ReadCloser, error) {
if url != f.url {
return nil, stderrors.New("not found")
}
return io.NopCloser(strings.NewReader(string(f.data))), nil
}
func (f *fakeArtifactFileService) SaveFile(_ context.Context, _ *multipart.FileHeader, _ uint64, _ string) (string, error) {
return "", nil
}
func (f *fakeArtifactFileService) SaveBytes(_ context.Context, _ []byte, _ uint64, _ string, _ bool) (string, error) {
return "", nil
}
func (f *fakeArtifactFileService) GetFileURL(_ context.Context, _ string) (string, error) {
return "", nil
}
func (f *fakeArtifactFileService) DeleteFile(_ context.Context, _ string) error {
return nil
}
// -----------------------------------------------------------------------------
// Router builder
// -----------------------------------------------------------------------------
func newArtifactTestRouter(h *Handler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
// Match the production route's wildcard names (see router.go — GET tree
// binds :id to align with /sessions/:id) so paramSessionID resolves via
// the same code path exercised in prod.
r.GET("/sessions/:id/artifacts", h.ListSessionArtifacts)
r.GET("/sessions/:id/messages/:message_id/artifacts", h.ListMessageArtifacts)
r.GET("/sessions/:id/messages/:message_id/artifacts/:index/download", h.DownloadMessageArtifact)
return r
}
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
func TestDownloadMessageArtifact_HappyPath(t *testing.T) {
sessionID := "sess-1"
messageID := "msg-1"
url := "fake://tenant-42/report.pptx"
body := []byte("PPTX-BYTES")
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, id string) (*types.Session, error) {
if id != sessionID {
return nil, apperrors.ErrSessionNotFound
}
return &types.Session{ID: id, TenantID: 42}, nil
},
},
messageService: &stubMessageServiceForArtifacts{
getMessage: func(_ context.Context, sid, mid string) (*types.Message, error) {
if sid != sessionID || mid != messageID {
return nil, nil
}
return &types.Message{
ID: mid, SessionID: sid,
Artifacts: types.MessageArtifacts{{
URL: url,
FileName: "报告.pptx", // non-ASCII to exercise RFC 5987 encoding
FileType: ".pptx",
FileSize: int64(len(body)),
}},
}, nil
},
},
fileService: &fakeArtifactFileService{url: url, data: body},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/0/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
}
if got := w.Body.String(); got != string(body) {
t.Fatalf("body = %q, want %q", got, string(body))
}
cd := w.Header().Get("Content-Disposition")
if !strings.HasPrefix(cd, "attachment;") {
t.Fatalf("Content-Disposition = %q, want attachment prefix", cd)
}
if !strings.Contains(cd, "filename*=UTF-8''") {
t.Fatalf("Content-Disposition = %q, want RFC 5987 filename*", cd)
}
if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {
t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
}
}
func TestDownloadMessageArtifact_SessionNotOwnedReturns404(t *testing.T) {
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return nil, apperrors.ErrSessionNotFound
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-x/messages/msg-x/artifacts/0/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", w.Code)
}
}
func TestDownloadMessageArtifact_IndexOutOfRange(t *testing.T) {
sessionID := "sess-1"
messageID := "msg-1"
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return &types.Session{ID: sessionID, TenantID: 42}, nil
},
},
messageService: &stubMessageServiceForArtifacts{
getMessage: func(_ context.Context, _, _ string) (*types.Message, error) {
return &types.Message{ID: messageID, SessionID: sessionID, Artifacts: types.MessageArtifacts{}}, nil
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/7/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 for out-of-range index", w.Code)
}
}
func TestDownloadMessageArtifact_InvalidIndex(t *testing.T) {
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return &types.Session{ID: "sess-1", TenantID: 42}, nil
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/not-a-number/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 for non-integer index", w.Code)
}
}
func TestListSessionArtifacts_StripsURL(t *testing.T) {
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return &types.Session{ID: "sess-1", TenantID: 42}, nil
},
},
messageService: &stubMessageServiceForArtifacts{
getSessionArtifact: func(_ context.Context, _ string) (types.MessageArtifacts, error) {
return types.MessageArtifacts{
{URL: "fake://internal/1", FileName: "a.txt", FileSize: 1, CreatedAt: time.Now()},
}, nil
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/artifacts", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
}
// The URL must not appear in the response body: it's an internal
// storage path and leaking it defeats the download endpoint's
// ownership check.
if strings.Contains(w.Body.String(), "fake://internal/1") {
t.Fatalf("response body leaked storage URL: %s", w.Body.String())
}
if !strings.Contains(w.Body.String(), "a.txt") {
t.Fatalf("response body missing file name: %s", w.Body.String())
}
}
func TestBuildAttachmentHeader_CJK(t *testing.T) {
// The RFC 5987 filename* segment must percent-encode every non-attr-char
// byte so downstream browsers preserve "报告.pptx" instead of mojibake.
got := buildAttachmentHeader("报告.pptx")
if !strings.Contains(got, "filename=") {
t.Fatalf("missing ASCII filename fallback: %q", got)
}
if !strings.Contains(got, "filename*=UTF-8''") {
t.Fatalf("missing RFC 5987 filename*: %q", got)
}
// Non-ASCII bytes must be percent-encoded (never appear literally).
if strings.ContainsRune(got, '报') {
t.Fatalf("filename* contains raw CJK: %q", got)
}
}

View File

@ -4,6 +4,7 @@ import (
stderrors "errors"
"net/http"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
@ -31,6 +32,10 @@ type Handler struct {
modelService interfaces.ModelService // Service for model management (VLM access)
attachmentProcessor *AttachmentProcessor // Processor for file attachments
temporaryDocuments interfaces.TemporaryDocumentService
// artifactCollector drains skill-generated files from the session sandbox
// after an agent turn completes. May be nil when the sandbox backend does
// not support artifact collection; handlers must check before using.
artifactCollector *service.ArtifactCollector
}
// NewHandler creates a new instance of Handler with all necessary dependencies
@ -51,6 +56,7 @@ func NewHandler(
documentReader interfaces.DocumentReader,
imageResolver *docparser.ImageResolver,
temporaryDocuments interfaces.TemporaryDocumentService,
artifactCollector *service.ArtifactCollector,
) *Handler {
return &Handler{
sessionService: sessionService,
@ -67,6 +73,7 @@ func NewHandler(
storageResolver: storageResolver,
modelService: modelService,
temporaryDocuments: temporaryDocuments,
artifactCollector: artifactCollector,
attachmentProcessor: NewAttachmentProcessor(
fileService,
documentReader,

View File

@ -285,13 +285,14 @@ func (h *Handler) createAssistantMessage(ctx context.Context, assistantMessage *
func (h *Handler) setupStreamHandler(
ctx context.Context,
sessionID, assistantMessageID, requestID string,
tenantID uint64,
receivedAt time.Time,
assistantMessage *types.Message,
eventBus *event.EventBus,
) *AgentStreamHandler {
streamHandler := NewAgentStreamHandler(
ctx, sessionID, assistantMessageID, requestID, receivedAt,
assistantMessage, h.streamManager, eventBus,
ctx, sessionID, assistantMessageID, requestID, tenantID, receivedAt,
assistantMessage, h.streamManager, eventBus, h.artifactCollector,
)
streamHandler.Subscribe()
return streamHandler

View File

@ -24,6 +24,11 @@ import (
"github.com/google/uuid"
)
const (
maxAttachmentUploadsPerRequest = 5
maxAttachmentUploadTotalBytes = int64(100 * 1024 * 1024)
)
// qaRequestContext holds all the common data needed for QA requests
type qaRequestContext struct {
ctx context.Context
@ -213,15 +218,17 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
if len(request.AttachmentUploads) > 0 {
logger.Infof(ctx, "[%s] processing %d attachment(s)", logPrefix, len(request.AttachmentUploads))
// MAX_FILE_SIZE_MB env (50MB default). See utils/filesize.go for
// why this is deploy-time-only rather than a runtime setting.
maxSizeMB := secutils.GetMaxFileSizeMB()
maxSize := maxSizeMB * 1024 * 1024
for i, upload := range request.AttachmentUploads {
if upload.FileSize > maxSize {
return nil, nil, errors.NewBadRequestError(
fmt.Sprintf("attachment %d exceeds size limit of %dMB", i+1, maxSizeMB))
}
// Decode first and validate actual bytes. Client-declared file_size is
// metadata only and must not be trusted for memory or sandbox limits.
maxSize := secutils.GetMaxFileSize()
decodedAttachments, decodeErr := decodeAndValidateAttachmentUploads(
request.AttachmentUploads,
maxAttachmentUploadsPerRequest,
maxSize,
maxAttachmentUploadTotalBytes,
)
if decodeErr != nil {
return nil, nil, errors.NewBadRequestError(decodeErr.Error())
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
@ -257,14 +264,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
go func(idx int, att AttachmentUpload) {
defer wg.Done()
data, err := DecodeBase64Attachment(att.Data)
if err != nil {
errChan <- fmt.Errorf("attachment %d decode failed: %w", idx+1, err)
return
}
processed, err := h.attachmentProcessor.ProcessAttachment(
attachmentRuntimeCtx, data, att.FileName, att.FileSize, tenantID, asrModelID,
attachmentRuntimeCtx, decodedAttachments[idx], att.FileName, int64(len(decodedAttachments[idx])), tenantID, asrModelID,
)
if err != nil {
errChan <- fmt.Errorf("attachment %d processing failed: %w", idx+1, err)
@ -391,6 +392,34 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
return reqCtx, &request, nil
}
func decodeAndValidateAttachmentUploads(
uploads []AttachmentUpload,
maxCount int,
maxFileBytes, maxTotalBytes int64,
) ([][]byte, error) {
if len(uploads) > maxCount {
return nil, fmt.Errorf("at most %d attachments are allowed per request", maxCount)
}
decoded := make([][]byte, len(uploads))
var total int64
for i, upload := range uploads {
data, err := DecodeBase64Attachment(upload.Data)
if err != nil {
return nil, fmt.Errorf("attachment %d decode failed: %w", i+1, err)
}
actualSize := int64(len(data))
if actualSize > maxFileBytes {
return nil, fmt.Errorf("attachment %d exceeds size limit of %d bytes", i+1, maxFileBytes)
}
total += actualSize
if total > maxTotalBytes {
return nil, fmt.Errorf("attachments exceed total request limit of %d bytes", maxTotalBytes)
}
decoded[i] = data
}
return decoded, nil
}
func buildMessageExecutionContext(
ctx context.Context,
agent *types.CustomAgent,
@ -597,6 +626,10 @@ func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool) *
logger.Infof(reqCtx.ctx, "Using effective tenant %d for shared agent (model/KB/MCP)", reqCtx.effectiveTenantID)
}
}
// The session's sandbox stays bound to the session owner even when the
// borrowed tenant above drives everything else, because DeleteSession tears
// that sandbox down from a request that only knows the session's tenant.
baseCtx = types.WithSandboxTenantID(baseCtx, reqCtx.session.TenantID)
// Create EventBus and cancellable context
eventBus := event.NewEventBus()
@ -625,7 +658,7 @@ func (h *Handler) setupSSEStream(reqCtx *qaRequestContext, generateTitle bool) *
// Setup stream handler
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
reqCtx.requestID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus)
reqCtx.requestID, reqCtx.session.TenantID, reqCtx.receivedAt, reqCtx.assistantMessage, eventBus)
// Generate title if needed
if generateTitle && reqCtx.session.Title == "" {

View File

@ -0,0 +1,62 @@
package session
import (
"encoding/base64"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func encodedAttachment(data string, declaredSize int64) AttachmentUpload {
return AttachmentUpload{
Data: base64.StdEncoding.EncodeToString([]byte(data)),
FileName: "file.txt",
FileSize: declaredSize,
}
}
func TestDecodeAndValidateAttachmentUploadsUsesActualBytes(t *testing.T) {
uploads := []AttachmentUpload{encodedAttachment("123456", 1)}
_, err := decodeAndValidateAttachmentUploads(uploads, 5, 5, 100)
require.Error(t, err)
assert.Contains(t, err.Error(), "exceeds size limit")
}
func TestDecodeAndValidateAttachmentUploadsBoundsCountAndTotal(t *testing.T) {
t.Run("count", func(t *testing.T) {
uploads := make([]AttachmentUpload, 6)
for i := range uploads {
uploads[i] = encodedAttachment("x", 1)
}
_, err := decodeAndValidateAttachmentUploads(uploads, 5, 10, 100)
require.Error(t, err)
assert.Contains(t, err.Error(), "at most 5")
})
t.Run("total", func(t *testing.T) {
uploads := []AttachmentUpload{
encodedAttachment(strings.Repeat("a", 6), 6),
encodedAttachment(strings.Repeat("b", 6), 6),
}
_, err := decodeAndValidateAttachmentUploads(uploads, 5, 10, 10)
require.Error(t, err)
assert.Contains(t, err.Error(), "total request limit")
})
}
func TestDecodeAndValidateAttachmentUploadsReturnsDecodedBytes(t *testing.T) {
decoded, err := decodeAndValidateAttachmentUploads(
[]AttachmentUpload{encodedAttachment("hello", 999)},
5,
10,
10,
)
require.NoError(t, err)
require.Len(t, decoded, 1)
assert.Equal(t, []byte("hello"), decoded[0])
}

View File

@ -62,6 +62,7 @@ type SystemHandler struct {
// singleton tenant.StorageEngineConfig. Optional — nil in partially-wired
// unit tests, in which case only the legacy config is consulted.
storageBackendRepo interfaces.StorageBackendRepository
sandboxConfigSvc sandboxConfigService
}
// NewSystemHandler creates a new system handler
@ -76,6 +77,7 @@ func NewSystemHandler(cfg *config.Config,
taskInspector interfaces.TaskInspector,
knowledgeSvc interfaces.KnowledgeService,
storageBackendRepo interfaces.StorageBackendRepository,
sandboxConfigSvc *service.TenantSandboxConfigService,
) *SystemHandler {
return &SystemHandler{
cfg: cfg,
@ -89,6 +91,7 @@ func NewSystemHandler(cfg *config.Config,
taskInspector: taskInspector,
knowledgeSvc: knowledgeSvc,
storageBackendRepo: storageBackendRepo,
sandboxConfigSvc: sandboxConfigSvc,
}
}

View File

@ -49,6 +49,7 @@ var imToolNameLabels = map[string]string{
"query_knowledge_graph": "知识图谱查询",
"read_skill": "读取技能",
"execute_skill_script": "执行技能脚本",
"shell_exec": "执行沙箱命令",
"data_analysis": "数据分析",
"data_schema": "数据结构",
"database_query": "数据库查询",

View File

@ -526,6 +526,13 @@ func CloneContext(ctx context.Context) context.Context {
types.SystemAdminContextKey,
types.LanguageContextKey,
types.SessionTenantIDContextKey,
types.SessionIDContextKey,
// SandboxTenantIDContextKey: the session owner's tenant, which the
// shared-agent path deliberately keeps separate from
// TenantIDContextKey. Dropping it here would silently re-key every
// session→sandbox binding onto the borrowed tenant, because
// setupSSEStream builds its async context through CloneContext.
types.SandboxTenantIDContextKey,
types.EmbedQueryContextKey,
types.EmbedVisitorContextKey,
// Keep the Langfuse trace alive across CloneContext boundaries so

View File

@ -212,3 +212,22 @@ func TestCloneContextPreservesTenantAPIKeyScope(t *testing.T) {
t.Fatalf("cloned scope = %#v, want key_id=7 scoped to kb-1", got)
}
}
// setupSSEStream builds its async context through CloneContext, so dropping
// this key here would silently re-key every session→sandbox binding onto the
// tenant a shared agent borrowed — stranding the MicroVM at session deletion.
func TestCloneContextPreservesSandboxTenantID(t *testing.T) {
t.Parallel()
const sessionOwner, agentOwner = uint64(7), uint64(99)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, agentOwner)
ctx = types.WithSandboxTenantID(ctx, sessionOwner)
cloned := CloneContext(ctx)
got, ok := types.SandboxTenantIDFromContext(cloned)
if !ok || got != sessionOwner {
t.Fatalf("SandboxTenantIDFromContext(cloned) = (%d, %v), want (%d, true)",
got, ok, sessionOwner)
}
}

View File

@ -144,6 +144,11 @@ var toolHandlePolicies = map[string]toolHandlePolicy{
// "url"/"knowledge_id" with unrelated semantics.
"read_skill": {},
"execute_skill_script": {},
// Sandbox shell/file tools return whatever a skill script produced, so they
// carry the same unknown-shape caveat as skill output above.
"shell_exec": {},
"list_sandbox_files": {},
"read_sandbox_file": {},
}
// HasToolPolicy reports whether a tool has an explicit model-handle policy.

View File

@ -56,6 +56,7 @@ type RouterParams struct {
MessageSuggestionHandler *handler.MessageSuggestionHandler
ModelHandler *handler.ModelHandler
ModelCredentialsHandler *handler.ModelCredentialsHandler
SandboxConfigHandler *handler.SandboxConfigHandler
EvaluationHandler *handler.EvaluationHandler
AuthHandler *handler.AuthHandler
InitializationHandler *handler.InitializationHandler
@ -262,6 +263,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterChatRoutes(v1, params.SessionHandler, rbacGuards)
RegisterMessageRoutes(v1, params.MessageHandler, rbacGuards)
RegisterModelRoutes(v1, params.ModelHandler, params.ModelCredentialsHandler, rbacGuards)
RegisterSandboxConfigRoutes(v1, params.SandboxConfigHandler, rbacGuards)
RegisterEvaluationRoutes(v1, params.EvaluationHandler, rbacGuards)
RegisterInitializationRoutes(v1, params.InitializationHandler, rbacGuards)
RegisterSystemRoutes(v1, params.SystemHandler, rbacGuards)

View File

@ -342,6 +342,7 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
RegisterWebSearchProviderRoutes(v1, &handler.WebSearchProviderHandler{}, &handler.WebSearchProviderCredentialsHandler{}, g)
RegisterVectorStoreRoutes(v1, &handler.VectorStoreHandler{}, g)
RegisterStorageBackendRoutes(v1, &handler.StorageBackendHandler{}, g)
RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, g)
RegisterEmbedChannelRoutes(v1, &handler.EmbedChannelHandler{}, g)
RegisterIMChannelRoutes(v1, &handler.IMHandler{}, g)
RegisterDataSourceRoutes(v1, &handler.DataSourceHandler{}, &handler.DataSourceCredentialsHandler{}, g)
@ -379,6 +380,38 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
}
}
func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, g)
cases := []struct {
method string
path string
}{
{http.MethodGet, "/api/v1/sandbox-configs"},
{http.MethodPost, "/api/v1/sandbox-configs"},
{http.MethodGet, "/api/v1/sandbox-configs/:id"},
{http.MethodPut, "/api/v1/sandbox-configs/:id"},
{http.MethodDelete, "/api/v1/sandbox-configs/:id"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/sandboxes"},
}
for _, tc := range cases {
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
if !policy.RequireFullAccess {
t.Fatal("sandbox config routes should require full access")
}
if len(policy.Capabilities) != 0 {
t.Fatalf("sandbox config routes must not be granted by a scoped capability: %#v", policy.Capabilities)
}
})
}
}
func TestTenantMemberRoutesDeclareManageMembersCapability(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}

View File

@ -220,6 +220,7 @@ func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g
systemRoutes.POST("/docreader/reconnect", g.Admin(), handler.ReconnectDocReader)
systemRoutes.GET("/storage-engine-status", g.Viewer(), handler.GetStorageEngineStatus)
systemRoutes.POST("/storage-engine-check", g.Admin(), handler.CheckStorageEngine)
systemRoutes.POST("/sandbox-check", g.Admin(), handler.CheckSandboxConfig)
}
}

View File

@ -79,6 +79,21 @@ func RegisterSessionRoutes(
sessions.POST("/:session_id/messages/:message_id/suggestions", suggestionHandler.Ensure)
sessions.POST("/:session_id/suggestion-events", suggestionHandler.RecordEvent)
}
// Skill-generated file artifacts. The list endpoints only expose
// metadata; the actual bytes are streamed via /artifacts/:index/download
// so the storage URL never appears on the wire.
//
// NOTE: gin builds a separate radix tree per HTTP verb but every
// path in the same tree must share the same wildcard name. The GET
// tree already binds :id via /sessions/:id (GetSession); reusing
// :id here (instead of :session_id) avoids the
// "wildcard conflicts" panic at route registration. The handlers
// read the URL param via c.Param("session_id") with a fallback to
// c.Param("id") for exactly this reason.
sessions.GET("/:id/artifacts", handler.ListSessionArtifacts)
sessions.GET("/:id/messages/:message_id/artifacts", handler.ListMessageArtifacts)
sessions.GET("/:id/messages/:message_id/artifacts/:index/download", handler.DownloadMessageArtifact)
}
}

View File

@ -40,6 +40,26 @@ func RegisterModelRoutes(
}
}
// Sandbox configs are workspace infrastructure that hold provider credentials.
// Scoped API keys cannot safely receive partial authority over them yet because
// mutation can strand remote sandboxes.
func RegisterSandboxConfigRoutes(
r *gin.RouterGroup,
h *handler.SandboxConfigHandler,
g *rbacGuards,
) {
configs := g.apiKeyGroup(r.Group("/sandbox-configs"), apiKeyFullAccess())
{
configs.GET("", g.Viewer(), h.List)
configs.PUT("/workspace-policy", g.Admin(), h.SetWorkspacePolicy)
configs.POST("", g.Admin(), h.Create)
configs.GET("/:id", g.Viewer(), h.Get)
configs.PUT("/:id", g.Admin(), h.Update)
configs.DELETE("/:id", g.Admin(), h.Delete)
configs.GET("/:id/sandboxes", g.Admin(), h.Inventory)
}
}
// RegisterEvaluationRoutes registers evaluation endpoints. Running an
// evaluation drives LLM calls (cost) and reads from KBs across the
// tenant; gate to Admin+ until product asks for a finer-grained

View File

@ -0,0 +1,81 @@
// Package sandbox: session-scoped capability interfaces.
//
// The Sandbox / Manager pair intentionally hides provider identity (Cube,
// E2B, Docker, Local) from the application layer. Higher layers should never
// branch on Manager.GetType() to decide whether a feature is supported —
// that couples them to a specific backend and, worse, misfires when a
// remote-capable manager transparently falls back to a stateless local
// sandbox.
//
// Instead, session-scoped features (shell execution, per-session file
// inspection, attachment staging) are advertised via the capability
// interfaces below. A manager may satisfy the underlying methods yet still
// return nil from the accessors on SessionCapabilityProvider when the
// current runtime configuration cannot honour that capability — for
// example, SessionBoundManager returns nil from every accessor after it
// falls back to LocalSandbox, ensuring the agent never surfaces
// tenant-isolated tools that would run on the WeKnora host.
package sandbox
import (
"context"
"time"
)
// SessionShellExecutor executes ad-hoc shell commands inside a session-
// scoped remote sandbox. Local/Docker backends do not implement it; a
// SessionBoundManager only surfaces it while the remote backend is active.
type SessionShellExecutor interface {
ExecShellCommand(
ctx context.Context,
sessionID string,
command string,
workDir string,
timeout time.Duration,
env map[string]string,
) (*ExecuteResult, error)
}
// SessionFileStore is the effective per-session filesystem view a manager
// offers callers that need to inspect, stage, or clean up files inside the
// session's remote sandbox. It is intentionally provider-neutral: entries
// use RemoteDirEntry / RemoteStatEntry, so E2B and Cube can implement it
// without touching the caller.
type SessionFileStore interface {
// EnsureSessionDir creates dir in the session's live sandbox. Silent
// no-op when no sandbox is bound yet; the next Execute call will
// materialise the directory during script upload.
EnsureSessionDir(ctx context.Context, sessionID, dir string) error
// ListSessionFiles walks dir recursively and returns file entries.
// Returns nil (no error) when the session has no live sandbox so
// callers can treat "no sandbox" and "empty output" uniformly.
ListSessionFiles(ctx context.Context, sessionID, dir string) ([]RemoteDirEntry, error)
// StatSessionFile returns metadata for a single file. Errors when the
// session has no bound sandbox — callers of this method already hold a
// path from a prior ListSessionFiles call.
StatSessionFile(ctx context.Context, sessionID, path string) (*RemoteStatEntry, error)
// ReadSessionFile downloads a file's contents. Same "no sandbox
// bound" contract as StatSessionFile.
ReadSessionFile(ctx context.Context, sessionID, path string) ([]byte, error)
// WriteSessionInputFile writes a durable attachment path into the
// session's remote sandbox, provisioning the sandbox on first call.
WriteSessionInputFile(ctx context.Context, sessionID, filePath string, content []byte) error
// RemoveSessionInputPath deletes a staged attachment. No-op when the
// session has no live sandbox.
RemoveSessionInputPath(ctx context.Context, sessionID, targetPath string) error
}
// SessionCapabilityProvider is implemented by managers that MAY offer
// session-scoped capabilities. Accessors return nil when the current
// runtime configuration cannot support that capability (e.g. remote
// provider unhealthy → LocalSandbox fallback). Application code should
// gate feature registration on non-nil accessor returns.
type SessionCapabilityProvider interface {
SessionShellExecutor() SessionShellExecutor
SessionFileStore() SessionFileStore
}

View File

@ -0,0 +1,62 @@
package sandbox
import (
"context"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// The connectivity probe dials endpoints an admin typed into an unsaved form,
// so it is the one client whose target is fully attacker-influenced within a
// workspace. Save-time validation cannot cover it: a hostname can resolve to a
// public address while the form is validated and to the cloud metadata service
// by the time the probe connects. Both providers must therefore refuse
// link-local at dial time, and they must do so even under the private-endpoint
// opt-in that self-hosted Cube deployments need.
func TestNewRemoteClientForCheckRefusesLinkLocalAtDial(t *testing.T) {
// The opt-in is deliberately ON: link-local must stay blocked regardless.
t.Setenv(AllowPrivateEndpointsEnv, "true")
const metadata = "http://169.254.169.254"
for _, tc := range []struct {
name string
cfg *Config
}{
{
name: "cube",
cfg: &Config{
Type: SandboxTypeCube,
CubeAPIURL: metadata,
CubeProxyURL: metadata,
CubeSandboxDomain: "cube.app",
CubeTemplate: "tpl-test",
},
},
{
name: "e2b",
cfg: &Config{
Type: SandboxTypeE2B,
E2BAPIKey: "key-test",
E2BAPIURL: metadata,
E2BTemplate: "base",
},
},
} {
t.Run(tc.name, func(t *testing.T) {
client, err := NewRemoteClientForCheck(tc.cfg)
require.NoError(t, err)
err = client.Health(context.Background())
require.Error(t, err, "probing the metadata service must fail")
// The guard rejects before any packet leaves, so the refusal - not
// a connection timeout - is what has to surface.
require.True(t,
strings.Contains(err.Error(), ErrUnsafeOutboundURL.Error()) ||
strings.Contains(err.Error(), "never routable"),
"expected the outbound guard to refuse the dial, got: %v", err)
})
}
}

View File

@ -0,0 +1,65 @@
// Package sandbox: description of the process-wide defaults a tenant inherits.
//
// A tenant that has not overridden a field runs on the deployment's global
// WEKNORA_SANDBOX_* configuration. The settings UI has to show what is actually
// in effect, otherwise an empty override set looks indistinguishable from
// "disabled" — and saving that impression would silently disable the sandbox.
//
// Secrets are deliberately never included here; only whether one is present.
package sandbox
// ProviderDefaults is the inheritable, non-secret configuration of one backend.
type ProviderDefaults struct {
APIURL string `json:"api_url,omitempty"`
ProxyURL string `json:"proxy_url,omitempty"`
SandboxDomain string `json:"sandbox_domain,omitempty"`
TemplateID string `json:"template_id,omitempty"`
APIKeyConfigured bool `json:"api_key_configured"`
HTTPTimeoutSec int `json:"http_timeout_sec,omitempty"`
SandboxTTLSec int `json:"sandbox_ttl_seconds,omitempty"`
}
// ConfigDefaults mirrors types.TenantSandboxConfig's shape so the UI can render
// inherited values as placeholders next to the tenant's own overrides.
type ConfigDefaults struct {
// SandboxType is the backend a tenant gets when it sets no override.
SandboxType string `json:"sandbox_type"`
DefaultTimeoutSec int `json:"default_timeout_sec,omitempty"`
DockerImage string `json:"docker_image,omitempty"`
Cube *ProviderDefaults `json:"cube,omitempty"`
E2B *ProviderDefaults `json:"e2b,omitempty"`
}
// DescribeDefaults projects a resolved global Config into its inheritable,
// secret-free description.
func DescribeDefaults(cfg *Config) *ConfigDefaults {
if cfg == nil {
return &ConfigDefaults{SandboxType: string(SandboxTypeDisabled)}
}
defaults := &ConfigDefaults{
SandboxType: string(cfg.Type),
DefaultTimeoutSec: int(cfg.DefaultTimeout.Seconds()),
DockerImage: cfg.DockerImage,
}
// Describe both remote backends regardless of the active mode: an admin
// switching a workspace to the other one still needs to see what it would
// inherit.
defaults.Cube = &ProviderDefaults{
APIURL: cfg.CubeAPIURL,
ProxyURL: cfg.CubeProxyURL,
SandboxDomain: cfg.CubeSandboxDomain,
TemplateID: cfg.CubeTemplate,
APIKeyConfigured: cfg.CubeAPIKey != "",
HTTPTimeoutSec: int(cfg.CubeHTTPTimeout.Seconds()),
SandboxTTLSec: int(cfg.CubeSandboxTTL.Seconds()),
}
defaults.E2B = &ProviderDefaults{
APIURL: cfg.E2BAPIURL,
SandboxDomain: cfg.E2BSandboxDomain,
TemplateID: cfg.E2BTemplate,
APIKeyConfigured: cfg.E2BAPIKey != "",
HTTPTimeoutSec: int(cfg.E2BHTTPTimeout.Seconds()),
SandboxTTLSec: int(cfg.E2BSandboxTTL.Seconds()),
}
return defaults
}

View File

@ -0,0 +1,71 @@
// Package sandbox: what makes an existing sandbox operable.
//
// Two groups of configuration fields decide whether the sandboxes a config has
// already created can still be acted on. This file names them in one place
// because the answer depends on which SDK carries which value:
//
// - Control plane (API URL, API key): every lifecycle call - list, delete,
// pause, resume, refresh timeout - is issued against it. Lose it and the
// sandboxes can no longer be reclaimed at all.
// - Data plane (sandbox domain, and for Cube the proxy endpoint): envd traffic
// is routed through it. Lose it and the sandboxes are still deletable but no
// longer usable, so every live session on the config fails at once.
//
// The split is a property of the clients in use, not a universal truth:
// github.com/matiasinsaurralde/go-e2b resolves the API base URL and the sandbox
// domain independently, whereas E2B's own JS/Python SDKs derive the API base from
// the domain (https://api.${domain}). Swapping that dependency would move the
// domain into the control-plane group.
package sandbox
import (
"github.com/Tencent/WeKnora/internal/types"
)
// SandboxIdentity is the comparable projection of a config: two configs with
// equal identities can operate each other's sandboxes.
type SandboxIdentity struct {
Provider string
// Control plane - whether an existing sandbox can still be reclaimed.
APIURL string
APIKey string
// Data plane - whether an existing sandbox can still be used.
SandboxDomain string
ProxyURL string
}
// IdentityOf projects a stored config onto its identity. Only the active
// provider's fields are read: a sub-struct left behind by an earlier provider
// switch says nothing about where today's sandboxes live.
//
// Because named configs inherit nothing, the stored row is the whole picture and
// no deployment baseline is consulted. Unknown type strings are compared verbatim
// rather than rejected: a typo yields an identity that matches nothing, which
// errs toward refusing the edit, and ParseSandboxType reports it on save.
//
// This runs no SSRF guard and returns no error on purpose. It answers "would this
// edit strand anything", a question that must stay answerable when the OLD
// endpoint no longer resolves — precisely the situation in which an admin needs
// to re-point the config. Validating the incoming URLs is the save path's job.
func IdentityOf(tenantCfg *types.TenantSandboxConfig) SandboxIdentity {
if tenantCfg == nil {
return SandboxIdentity{}
}
identity := SandboxIdentity{Provider: tenantCfg.SandboxType}
switch SandboxType(tenantCfg.SandboxType) {
case SandboxTypeCube:
if cube := tenantCfg.Cube; cube != nil {
identity.APIURL, identity.APIKey = cube.APIURL, cube.APIKey
identity.SandboxDomain = cube.SandboxDomain
identity.ProxyURL = cube.ProxyURL
}
case SandboxTypeE2B:
if e2bCfg := tenantCfg.E2B; e2bCfg != nil {
identity.APIURL, identity.APIKey = e2bCfg.APIURL, e2bCfg.APIKey
identity.SandboxDomain = e2bCfg.SandboxDomain
}
}
return identity
}

View File

@ -0,0 +1,75 @@
package sandbox
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/types"
)
// Identity comes from the stored row alone. Nothing about the deployment can
// change it, which is what makes "did this edit strand a sandbox" answerable
// without reaching for WEKNORA_SANDBOX_*.
func TestIdentityOfReadsStoredFieldsOnly(t *testing.T) {
identity := IdentityOf(&types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIURL: "https://api.e2b.app", SandboxDomain: "e2b.app", APIKey: "key-a",
},
})
require.Equal(t, SandboxIdentity{
Provider: "e2b",
APIURL: "https://api.e2b.app",
APIKey: "key-a",
SandboxDomain: "e2b.app",
}, identity)
}
// A blank field is blank, not "whatever the deployment runs". Two configs that
// differ only in what they spell out are therefore different identities.
func TestIdentityOfDoesNotInherit(t *testing.T) {
blank := IdentityOf(&types.TenantSandboxConfig{SandboxType: "cube"})
spelledOut := IdentityOf(&types.TenantSandboxConfig{
SandboxType: "cube",
Cube: &types.CubeSandboxConfig{
APIURL: DefaultCubeAPIURL, ProxyURL: DefaultCubeProxyURL,
SandboxDomain: DefaultCubeSandboxDomain,
},
})
require.Equal(t, SandboxIdentity{Provider: "cube"}, blank)
require.NotEqual(t, blank, spelledOut)
require.Equal(t, DefaultCubeProxyURL, spelledOut.ProxyURL)
}
// Only the active provider describes where the sandboxes are; the other
// sub-struct is leftover state from an earlier switch.
func TestIdentityOfReadsOnlyActiveProvider(t *testing.T) {
cfg := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{APIKey: "e2b-key"},
Cube: &types.CubeSandboxConfig{APIKey: "stale-cube-key"},
}
identity := IdentityOf(cfg)
require.Equal(t, "e2b-key", identity.APIKey)
require.Empty(t, identity.ProxyURL, "Cube's data plane is irrelevant while E2B is active")
}
// Backends that hold no remote resources carry no credentials, but switching
// between them still has to register as a change.
func TestIdentityOfLocalBackendsCarryProviderOnly(t *testing.T) {
docker := IdentityOf(&types.TenantSandboxConfig{SandboxType: "docker"})
local := IdentityOf(&types.TenantSandboxConfig{SandboxType: "local"})
require.Equal(t, SandboxIdentity{Provider: "docker"}, docker)
require.NotEqual(t, docker, local)
}
// A nil config must not panic: Update compares against it when creating.
func TestIdentityOfToleratesNilConfig(t *testing.T) {
require.Equal(t, SandboxIdentity{}, IdentityOf(nil))
}

View File

@ -0,0 +1,77 @@
// Package sandbox: what a named backend config must carry on its own.
//
// A named config is self-contained. Nothing is inherited from the deployment
// WEKNORA_SANDBOX_* baseline, which exists only to serve agents that selected no
// config at all. The trade for that clarity is that every value the provider
// client cannot synthesize has to be present in the config itself, so this file
// names those values once and both the save path and the resolve path check
// against it.
//
// Two classes are deliberately NOT required:
//
// - Credentials a self-hosted deployment does not use. The common single-node
// Cube setup runs unauthenticated, so CubeAPIKey stays optional.
// - Values the SDK resolves by itself. go-e2b defaults both the API base URL
// and the sandbox domain when they are left empty, so demanding them would
// force operators to spell out constants they cannot verify.
//
// Everything else is required precisely because its absence fails late and
// obscurely: a missing Cube proxy URL or sandbox domain still creates a sandbox
// and only breaks when envd traffic is routed, which reads as a provider outage
// rather than a typo in the form.
package sandbox
import (
"errors"
"fmt"
"strings"
)
// ErrSandboxConfigIncomplete marks a named config that cannot build a working
// client because required fields are empty. Callers map it onto 400.
var ErrSandboxConfigIncomplete = errors.New("sandbox: config is missing required fields")
// MissingRequiredFields lists the fields cfg fails to supply for its own
// provider, named after the JSON keys the API and the settings form use so the
// message can be surfaced without translation. Backends that hold no endpoint
// of their own (docker / local / disabled) require nothing.
func MissingRequiredFields(cfg *Config) []string {
if cfg == nil {
return nil
}
var missing []string
require := func(field, value string) {
if strings.TrimSpace(value) == "" {
missing = append(missing, field)
}
}
switch cfg.Type {
case SandboxTypeCube:
require("api_url", cfg.CubeAPIURL)
require("proxy_url", cfg.CubeProxyURL)
require("sandbox_domain", cfg.CubeSandboxDomain)
require("template_id", cfg.CubeTemplate)
case SandboxTypeE2B:
require("api_key", cfg.E2BAPIKey)
require("template_id", cfg.E2BTemplate)
}
return missing
}
// RequireCompleteConfig is the error form of MissingRequiredFields, shared by
// the save path and the resolve path so both reject the same configs with the
// same wording.
func RequireCompleteConfig(cfg *Config) error {
missing := MissingRequiredFields(cfg)
if len(missing) == 0 {
return nil
}
provider := ""
if cfg != nil {
provider = string(cfg.Type)
}
return fmt.Errorf(
"%w: %s backend requires %s",
ErrSandboxConfigIncomplete, provider, strings.Join(missing, ", "),
)
}

View File

@ -0,0 +1,114 @@
// Package sandbox: per-config sandbox inventory.
//
// Identity changes (provider / endpoint / API key) and config deletion both
// need one question answered authoritatively: does this config still own live
// sandboxes on the provider?
//
// The binding store cannot answer it. Bindings go missing exactly when leaks
// happen - a CAS rebind overwrites the old sandbox ID, Redis evicts, a process
// restarts - so trusting them under-reports in the one direction that costs
// money. The provider's own listing is the source of truth.
package sandbox
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/types"
)
// ConfigSandboxLister is the read half of the provider client.
type ConfigSandboxLister interface {
List(ctx context.Context, filter RemoteListFilter) ([]RemoteSandboxSummary, error)
}
// ConfigSandboxClient adds deletion, needed to release an inventory.
type ConfigSandboxClient interface {
ConfigSandboxLister
Delete(ctx context.Context, sandboxID string) error
}
// NormalizeConfigID maps the empty config ID onto the sentinel used in
// metadata, so "the deployment default config" is addressable like any other.
func NormalizeConfigID(configID string) string {
if strings.TrimSpace(configID) == "" {
return types.SandboxConfigIDGlobalDefault
}
return configID
}
// MetadataSessionIDKey returns the provider metadata key used for session IDs.
func MetadataSessionIDKey() string {
return remoteMetadataSessionID
}
// configSandboxFilter narrows a listing to one workspace's one config.
func configSandboxFilter(tenantID uint64, configID string) RemoteListFilter {
return RemoteListFilter{
Metadata: map[string]string{
remoteMetadataTenantID: strconv.FormatUint(tenantID, 10),
remoteMetadataConfigID: NormalizeConfigID(configID),
},
// Paused sandboxes are not idle leftovers: they bill, and a session
// expects to resume them. Omitting them would report "nothing here"
// right before the credentials that could delete them are replaced.
States: []RemoteSandboxState{RemoteStateRunning, RemoteStatePaused},
}
}
// ListConfigSandboxes returns the sandboxes a config currently owns.
func ListConfigSandboxes(
ctx context.Context,
client ConfigSandboxLister,
tenantID uint64,
configID string,
) ([]RemoteSandboxSummary, error) {
if client == nil {
return nil, fmt.Errorf("sandbox: listing requires a client")
}
summaries, err := client.List(ctx, configSandboxFilter(tenantID, configID))
if err != nil {
return nil, fmt.Errorf(
"sandbox: list workspace %d config %q sandboxes: %w",
tenantID, NormalizeConfigID(configID), err)
}
return summaries, nil
}
// ReleaseConfigSandboxes deletes every sandbox the config owns and reports how
// many went away.
//
// This is deliberately NOT exposed as an admin action. Its one caller is the
// sweep that runs immediately after a config's credentials are overwritten,
// using the outgoing credentials still held in memory — the only remaining
// moment those sandboxes can be reached at all. An admin blocked from editing a
// config is instead told to end the owning sessions or create a second config.
//
// One undeletable sandbox does not abort the sweep - partial progress is
// strictly better than none - but the failures ARE returned. Swallowing them
// would leave a paused instance billing on credentials that no longer exist
// anywhere, with no record of which sandbox it was.
func ReleaseConfigSandboxes(
ctx context.Context,
client ConfigSandboxClient,
tenantID uint64,
configID string,
) (int, error) {
summaries, err := ListConfigSandboxes(ctx, client, tenantID, configID)
if err != nil {
return 0, err
}
deleted := 0
var failures []error
for _, summary := range summaries {
if err := client.Delete(ctx, summary.ID); err != nil {
failures = append(failures, fmt.Errorf("delete sandbox %s: %w", summary.ID, err))
continue
}
deleted++
}
return deleted, errors.Join(failures...)
}

Some files were not shown because too many files have changed in this diff Show More