Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(sandbox): remove the Local host-process backend
wizardchen7fda02637c59
diff --git a/docs/agent-skills.md b/docs/agent-skills.mdindex bb1377cd3..a809f5900 100644--- a/docs/agent-skills.md+++ b/docs/agent-skills.md@@ -128,12 +128,11 @@ Sandbox 不再读取 `WEKNORA_SANDBOX_*` 环境变量。后端、凭据、模板### Sandbox 模式-Docker、Local、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接检查和智能体选择接口管理。CubeSandbox / E2B 的集群搭建和设置页接入流程见 [WeKnora 沙箱集群与标准模板](sandbox-cluster.md)。设置页会通过当前连接拉取模板目录;若没有 WeKnora 标准模板,后端会从标准镜像发起创建,用户无需复制模板 ID。+Docker、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接检查和智能体选择接口管理。CubeSandbox / E2B 的集群搭建和设置页接入流程见 [WeKnora 沙箱集群与标准模板](sandbox-cluster.md)。设置页会通过当前连接拉取模板目录;若没有 WeKnora 标准模板,后端会从标准镜像发起创建,用户无需复制模板 ID。| 模式 | 状态 | 说明 ||------|------|------|| `docker` | 稳定 | 单机 Docker daemon;会话级持久(一个会话一个长驻容器),支持多机 WeKnora 副本(需 Redis),但沙箱都落在同一台 daemon 上。见 [Docker 沙箱后端](sandbox-docker-backend.md) |-| `local` | 开发 | 直接在 WeKnora 服务主机执行;无容器/MicroVM 隔离,不保留会话绑定 || `cube` | 稳定 | Tencent CubeSandbox MicroVM;会话级持久,支持多机(需 Redis) || `e2b` | 稳定 | E2B 云端 MicroVM;会话级持久,支持多机(需 Redis);依赖第三方 SDK go-e2b |@@ -569,24 +568,6 @@ docker run --rm \python scripts/analyze.py input.pdf```-### Local 沙箱--Local 模式提供基础保护:--- **命令白名单**:仅允许特定解释器-- **工作目录限制**:限定在 Skill 目录-- **环境变量过滤**:仅传递安全变量-- **超时控制**:默认 30 秒超时-- **路径遍历防护**:防止访问 Skill 目录外文件-- **脚本预校验**:执行前进行安全校验--**允许的命令**:-- `python`, `python3`-- `node`, `nodejs`-- `bash`, `sh`-- `ruby`-- `go run`-## API 参考### SkillManager@@ -689,10 +670,9 @@ go run ./cmd/skills-demo/main.go### 脚本执行失败-1. 检查 `sandbox_mode` 配置+1. 检查沙箱后端配置2. Docker 模式:确认 Docker 服务运行中-3. Local 模式:确认解释器已安装-4. 检查脚本权限和语法+3. 检查脚本权限和语法### 元数据验证错误diff --git a/docs/docs.go b/docs/docs.goindex 60f51e691..b6119a6b8 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -21418,7 +21418,7 @@ const docTemplate = `{}},"sandbox_type": {- "description": "SandboxType selects the sandbox backend. Named configs may use \"cube\",\n\"e2b\", \"docker\", or \"local\". \"disabled\" is reserved for the hidden\nworkspace policy row.",+ "description": "SandboxType is cube, e2b, or docker; disabled is the hidden policy row.","type": "string"},"skill_image": {diff --git a/docs/sandbox-cluster.md b/docs/sandbox-cluster.mdindex b27613f39..dea6b34b9 100644--- a/docs/sandbox-cluster.md+++ b/docs/sandbox-cluster.md@@ -1,6 +1,6 @@# WeKnora 沙箱集群与标准模板-本文面向部署和平台管理员,说明如何把 CubeSandbox 或 E2B 接入 WeKnora。Docker、Local、CubeSandbox、E2B 都在同一个空间设置页面通过同一套配置与检查接口管理;只有远端后端需要本文所述的集群和模板准备。普通智能体使用者不需要搭建模板,也不应该逐项猜测运行环境。+本文面向部署和平台管理员,说明如何把 CubeSandbox 或 E2B 接入 WeKnora。Docker、CubeSandbox、E2B 都在同一个空间设置页面通过同一套配置与检查接口管理;只有远端后端需要本文所述的集群和模板准备。普通智能体使用者不需要搭建模板,也不应该逐项猜测运行环境。## 谁负责什么diff --git a/docs/swagger.json b/docs/swagger.jsonindex 17ed9bc50..b2b78777c 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -21411,7 +21411,7 @@}},"sandbox_type": {- "description": "SandboxType selects the sandbox backend. Named configs may use \"cube\",\n\"e2b\", \"docker\", or \"local\". \"disabled\" is reserved for the hidden\nworkspace policy row.",+ "description": "SandboxType is cube, e2b, or docker; disabled is the hidden policy row.","type": "string"},"skill_image": {diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex 334ca9c22..9d04c7e0b 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -3828,10 +3828,7 @@ definitions:place secrets here that scripts must not access."type: objectsandbox_type:- description: |-- SandboxType selects the sandbox backend. Named configs may use "cube",- "e2b", "docker", or "local". "disabled" is reserved for the hidden- workspace policy row.+ description: SandboxType is cube, e2b, or docker; disabled is the hidden policy row.type: stringskill_image:allOf:diff --git "a/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md" "b/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md"index dac2717f4..25418c898 100644--- "a/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md"+++ "b/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md"@@ -76,7 +76,7 @@ my-skill/### Sandbox 配置-空间管理员在「设置 → 沙箱后端」中统一维护 Docker、Local、CubeSandbox 或 E2B 配置。远端模板从目标集群实时获取;缺少 WeKnora 标准模板时由系统自动创建。智能体在编辑页选择一份空间配置,没有选择时不执行技能脚本。Docker/Local 每次独立执行,CubeSandbox/E2B 则保留会话级沙箱。+空间管理员在「设置 → 沙箱后端」中统一维护 Docker、CubeSandbox 或 E2B 配置。远端模板从目标集群实时获取;缺少 WeKnora 标准模板时由系统自动创建。智能体在编辑页选择一份空间配置,没有选择时不执行技能脚本。Docker、CubeSandbox、E2B 均保留会话级沙箱。## 配置示例diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.tsindex 5e6ba451b..aac241edf 100644--- a/frontend/src/api/system/index.ts+++ b/frontend/src/api/system/index.ts@@ -858,7 +858,7 @@ export interface SandboxInventory {}/** Sandbox backends managed as named workspace configurations. */-export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b', 'docker', 'local'] as const+export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b', 'docker'] as constexport function isNamedSandboxBackend(type: string): boolean {return (NAMED_SANDBOX_BACKEND_TYPES as readonly string[]).includes(type)diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vueindex b7846ea8b..0abb3246d 100644--- a/frontend/src/components/SandboxConfigEditorDrawer.vue+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue@@ -208,38 +208,35 @@<section v-if="currentStepKey === 'connection' && !isRemoteBackend" class="setting-drawer__section"><h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionRuntimeEnvironment') }}</h4>- <template v-if="backend === 'docker'">- <div class="weknora-template-card is-active">- <SandboxBackendBadge type="docker" />- <div class="weknora-template-card__content">- <div class="weknora-template-card__title-row">- <span class="weknora-template-card__title">{{ $t('settings.sandbox.weknoraDockerImage') }}</span>- <t-tag theme="primary" variant="light" size="small">{{ $t('settings.sandbox.recommendedTag') }}</t-tag>- </div>- <p>{{ $t('settings.sandbox.weknoraDockerImageHint') }}</p>+ <div class="weknora-template-card is-active">+ <SandboxBackendBadge type="docker" />+ <div class="weknora-template-card__content">+ <div class="weknora-template-card__title-row">+ <span class="weknora-template-card__title">{{ $t('settings.sandbox.weknoraDockerImage') }}</span>+ <t-tag theme="primary" variant="light" size="small">{{ $t('settings.sandbox.recommendedTag') }}</t-tag></div>+ <p>{{ $t('settings.sandbox.weknoraDockerImageHint') }}</p></div>- <t-form-item :label="requiredLabel('dockerImage')" :status="fieldStatus('image')"- :tips="fieldTip('image')">- <t-input v-model="docker.image" placeholder="wechatopenai/weknora-sandbox:latest"- :disabled="retargetFrozen" @input="onFieldInput('image')" />- <p v-if="retargetFrozen" class="section-help section-help--field">- {{ hasSkillSnapshot- ? $t('settings.sandbox.templateLockedBySkills')- : $t('settings.sandbox.templateLockedByInFlight') }}- </p>- </t-form-item>- <t-form-item :label="$t('settings.sandbox.dockerHost')" :help="$t('settings.sandbox.dockerHostHelp')">- <t-input v-model="docker.host" placeholder="unix:///var/run/docker.sock"- :disabled="retargetFrozen" @input="onFieldInput('host')" />- </t-form-item>- <t-form-item :label="$t('settings.sandbox.dockerTlsCertPath')"- :help="$t('settings.sandbox.dockerTlsCertPathHelp')">- <t-input v-model="docker.tls_cert_path" placeholder="/etc/weknora/docker-certs"- :disabled="retargetFrozen" @input="onFieldInput('tls_cert_path')" />- </t-form-item>- </template>- <t-alert v-else theme="warning" class="compact-alert" :message="$t('settings.sandbox.localRuntimeWarning')" />+ </div>+ <t-form-item :label="requiredLabel('dockerImage')" :status="fieldStatus('image')"+ :tips="fieldTip('image')">+ <t-input v-model="docker.image" placeholder="wechatopenai/weknora-sandbox:latest"+ :disabled="retargetFrozen" @input="onFieldInput('image')" />+ <p v-if="retargetFrozen" class="section-help section-help--field">+ {{ hasSkillSnapshot+ ? $t('settings.sandbox.templateLockedBySkills')+ : $t('settings.sandbox.templateLockedByInFlight') }}+ </p>+ </t-form-item>+ <t-form-item :label="$t('settings.sandbox.dockerHost')" :help="$t('settings.sandbox.dockerHostHelp')">+ <t-input v-model="docker.host" placeholder="unix:///var/run/docker.sock"+ :disabled="retargetFrozen" @input="onFieldInput('host')" />+ </t-form-item>+ <t-form-item :label="$t('settings.sandbox.dockerTlsCertPath')"+ :help="$t('settings.sandbox.dockerTlsCertPathHelp')">+ <t-input v-model="docker.tls_cert_path" placeholder="/etc/weknora/docker-certs"+ :disabled="retargetFrozen" @input="onFieldInput('tls_cert_path')" />+ </t-form-item></section><section v-if="currentStepKey === 'template'" class="setting-drawer__section">@@ -572,7 +569,7 @@ const wizardStep = ref(0)let templatePollTimer: ReturnType<typeof setTimeout> | undefined// Remote backends additionally expose a template catalog and control-plane-// settings. All four backends still share the same save/check API.+// settings. Cube, E2B and Docker still share the same save/check API.const isRemoteBackend = computed(() => backend.value === 'cube' || backend.value === 'e2b')const hasImageCatalog = computed(() => isRemoteBackend.value || backend.value === 'docker')const currentTemplateId = computed(() => (@@ -591,11 +588,7 @@ const wizardSteps = computed<Array<{ key: SandboxStepKey; title: string }>>(() =steps.push({ key: 'template', title: t('settings.sandbox.stepTemplate') })}steps.push({ key: 'runtime', title: t('settings.sandbox.stepRuntime') })- // Skills are baked into the config's snapshot image. Local configs end- // at runtime rather than showing a step that could never do anything.- if (isRemoteBackend.value || backend.value === 'docker') {- steps.push({ key: 'skills', title: t('settings.sandbox.stepSkills') })- }+ steps.push({ key: 'skills', title: t('settings.sandbox.stepSkills') })return steps})const currentStepKey = computed<SandboxStepKey>(() => wizardSteps.value[wizardStep.value]?.key || 'connection')@@ -613,7 +606,7 @@ const primaryText = computed(() => {}return t('common.save')})-// Deep check needs the fields that actually get probed. Docker/local collect+// Deep check needs the fields that actually get probed. Docker collects// the image on the connection step; Cube/E2B still have an empty template_id// there, so the action waits until the template step.const canDeepCheck = computed(() => {@@ -707,7 +700,6 @@ const REQUIRED_FIELDS: Record<string, string[]> = {cube: ['api_url', 'proxy_url', 'sandbox_domain', 'template_id'],e2b: ['api_key', 'template_id'],docker: ['image'],- local: [],}const fieldErrors = ref<Record<string, string>>({})diff --git a/frontend/src/components/settings/SandboxBackendBadge.vue b/frontend/src/components/settings/SandboxBackendBadge.vueindex ff507cc6e..2baa3a5c9 100644--- a/frontend/src/components/settings/SandboxBackendBadge.vue+++ b/frontend/src/components/settings/SandboxBackendBadge.vue@@ -19,7 +19,7 @@ const props = withDefaults(defineProps<{const logo = computed(() => providerLogo('sandbox', props.type))const iconName = computed(() => {- if (props.type === 'cube' || props.type === 'local') return 'server'+ if (props.type === 'cube') return 'server'if (props.type === 'disabled') return 'minus-circle'return 'cloud'})@@ -69,11 +69,6 @@ const badgeStyle = computed((): Record<string, string> => (color: #1d63ed;}-.sandbox-badge--local {- background: rgba(17, 128, 83, 0.1);- color: #118053;-}-.sandbox-badge--mono::before {content: '';background-color: currentColor;diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 4146872dc..bf98ad977 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1059,8 +1059,8 @@ export default {title: 'Skill Sandbox',description: 'Manage isolated runtimes for agent skill scripts. Each agent can pick one workspace config.',pageHintTitle: 'What is a skill sandbox?',- pageHint: 'A skill sandbox is the isolated environment where agent skill scripts run. A workspace can have several configs (Docker, E2B, CubeSandbox, or a local process); each agent picks one. Scripts stay disabled until a config is selected.',- editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',+ pageHint: 'A skill sandbox is the isolated environment where agent skill scripts run. A workspace can have several configs (Docker, E2B, CubeSandbox); each agent picks one. Scripts stay disabled until a config is selected.',+ editorDescription: 'Configure a workspace runtime. Docker, CubeSandbox, and E2B use the same management flow.',stepConnection: 'Connect',stepTemplate: 'Template',stepRuntime: 'Runtime',@@ -1086,7 +1086,6 @@ export default {cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',e2b: 'Managed MicroVM service or an E2B-compatible deployment',docker: 'Keep a long-lived container per session on this WeKnora host; scripts and files stay in that container',- local: 'Run scripts directly in the WeKnora server process environment',},addConfig: 'Add sandbox',viewClusterGuide: 'Cluster setup guide',@@ -1139,7 +1138,6 @@ export default {weknoraTemplateTitle: 'WeKnora standard template',weknoraDockerImage: 'WeKnora standard image',weknoraDockerImageHint: 'Each session gets its own long-lived container. Scripts, shell commands and files all share it until the session ends or the idle timeout reclaims it.',- localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',recommendedTag: 'Recommended',@@ -1152,7 +1150,6 @@ export default {cardPrivateEndpoints: 'Private endpoints allowed',templateNotConfigured: 'Template not configured',imageNotConfigured: 'Image not configured',- localRuntimeSummary: 'WeKnora server process',templateApplied: 'Applied',refreshTemplates: 'Refresh templates',templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',@@ -1271,12 +1268,10 @@ export default {skipReasons: {needs_deep_check: 'Needs full verification',control_plane_unreachable: 'Skipped: control plane unreachable',- environment_unavailable: 'Skipped: runtime unavailable',sandbox_not_created: 'Skipped: sandbox was not created',sandbox_exec_failed: 'Skipped: in-sandbox execution failed',},checks: {- environment_available: 'Runtime availability',client_build: 'Client construction',api_url_reachable: 'Endpoint reachability',credential_valid: 'Credential validity',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex b8cf617a7..341c36119 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -4912,8 +4912,8 @@ export default {title: '스킬 샌드박스',description: '에이전트 스킬 스크립트의 격리 실행 환경을 관리합니다. 각 에이전트는 워크스페이스 설정을 하나 선택할 수 있습니다.',pageHintTitle: '스킬 샌드박스란?',- pageHint: '스킬 샌드박스는 에이전트 스킬 스크립트가 실행되는 격리 환경입니다. 워크스페이스에 Docker, E2B, CubeSandbox 또는 로컬 프로세스 설정을 여러 개 둘 수 있고, 각 에이전트가 하나를 선택합니다. 선택하지 않으면 스크립트는 실행되지 않습니다.',- editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',+ pageHint: '스킬 샌드박스는 에이전트 스킬 스크립트가 실행되는 격리 환경입니다. 워크스페이스에 Docker, E2B, CubeSandbox 설정을 여러 개 둘 수 있고, 각 에이전트가 하나를 선택합니다. 선택하지 않으면 스크립트는 실행되지 않습니다.',+ editorDescription: 'Configure a workspace runtime. Docker, CubeSandbox, and E2B use the same management flow.',stepConnection: 'Connect',stepTemplate: 'Template',stepRuntime: 'Runtime',@@ -4939,7 +4939,6 @@ export default {cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',e2b: 'Managed MicroVM service or an E2B-compatible deployment',docker: '이 WeKnora 호스트의 Docker에서 세션마다 장수명 컨테이너를 유지합니다. 스크립트와 파일이 같은 컨테이너에 남습니다',- local: 'Run scripts directly in the WeKnora server process environment',},addConfig: '샌드박스 추가',viewClusterGuide: 'Cluster setup guide',@@ -4992,7 +4991,6 @@ export default {weknoraTemplateTitle: 'WeKnora standard template',weknoraDockerImage: 'WeKnora standard image',weknoraDockerImageHint: 'Each session gets its own long-lived container. Scripts, shell commands and files all share it until the session ends or the idle timeout reclaims it.',- localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',recommendedTag: 'Recommended',@@ -5005,7 +5003,6 @@ export default {cardEnvVars: '환경 변수 {count}개',cardPrivateEndpoints: '사설망 접근 허용',imageNotConfigured: 'Image not configured',- localRuntimeSummary: 'WeKnora server process',templateApplied: 'Applied',refreshTemplates: 'Refresh templates',templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',@@ -5123,13 +5120,11 @@ export default {skipReasons: {needs_deep_check: '전체 검증 필요',control_plane_unreachable: '컨트롤 플레인에 연결할 수 없어 건너뜀',- environment_unavailable: '실행 환경을 사용할 수 없어 건너뜀',sandbox_not_created: '샌드박스가 생성되지 않아 건너뜀',sandbox_exec_failed: '샌드박스 내 실행 실패로 건너뜀',},noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',checks: {- environment_available: 'Runtime availability',client_build: 'Client construction',api_url_reachable: 'Endpoint reachability',credential_valid: 'Credential validity',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex ca0b762a6..f18713ec0 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -4912,8 +4912,8 @@ export default {title: 'Песочница навыков',description: 'Управление изолированными средами для скриптов навыков агента. Каждый агент может выбрать одну конфигурацию пространства.',pageHintTitle: 'Что такое песочница навыков?',- pageHint: 'Песочница навыков — изолированная среда, в которой выполняются скрипты навыков агента. В пространстве можно создать несколько конфигураций (Docker, E2B, CubeSandbox или локальный процесс); каждый агент выбирает одну. Пока конфигурация не выбрана, скрипты не выполняются.',- editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',+ pageHint: 'Песочница навыков — изолированная среда, в которой выполняются скрипты навыков агента. В пространстве можно создать несколько конфигураций (Docker, E2B, CubeSandbox); каждый агент выбирает одну. Пока конфигурация не выбрана, скрипты не выполняются.',+ editorDescription: 'Configure a workspace runtime. Docker, CubeSandbox, and E2B use the same management flow.',stepConnection: 'Connect',stepTemplate: 'Template',stepRuntime: 'Runtime',@@ -4939,7 +4939,6 @@ export default {cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',e2b: 'Managed MicroVM service or an E2B-compatible deployment',docker: 'Держит долгоживущий контейнер на каждую сессию на этом хосте WeKnora; скрипты и файлы остаются в том же контейнере',- local: 'Run scripts directly in the WeKnora server process environment',},addConfig: 'Добавить песочницу',viewClusterGuide: 'Cluster setup guide',@@ -4992,7 +4991,6 @@ export default {weknoraTemplateTitle: 'WeKnora standard template',weknoraDockerImage: 'WeKnora standard image',weknoraDockerImageHint: 'Each session gets its own long-lived container. Scripts, shell commands and files all share it until the session ends or the idle timeout reclaims it.',- localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',recommendedTag: 'Recommended',@@ -5005,7 +5003,6 @@ export default {cardEnvVars: 'Переменных окружения: {count}',cardPrivateEndpoints: 'Разрешён доступ к частной сети',imageNotConfigured: 'Image not configured',- localRuntimeSummary: 'WeKnora server process',templateApplied: 'Applied',refreshTemplates: 'Refresh templates',templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',@@ -5123,13 +5120,11 @@ export default {skipReasons: {needs_deep_check: 'Нужна полная проверка',control_plane_unreachable: 'Пропущено: плоскость управления недоступна',- environment_unavailable: 'Пропущено: среда выполнения недоступна',sandbox_not_created: 'Пропущено: песочница не создана',sandbox_exec_failed: 'Пропущено: выполнение в песочнице не удалось',},noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',checks: {- environment_available: 'Runtime availability',client_build: 'Client construction',api_url_reachable: 'Endpoint reachability',credential_valid: 'Credential validity',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 1a16c3697..f578e2649 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -4914,8 +4914,8 @@ export default {title: '技能沙箱',description: '管理智能体技能脚本的隔离运行环境,每个智能体可以选择一份空间配置。',pageHintTitle: '什么是技能沙箱?',- pageHint: '技能沙箱是智能体执行技能脚本的隔离环境。一个空间可以添加多份配置(Docker、E2B、CubeSandbox 或本地进程),每个智能体选择一份;未选择时不会执行技能脚本。',- editorDescription: '配置空间运行环境,Docker、本地进程、CubeSandbox 和 E2B 使用同一套管理流程。',+ pageHint: '技能沙箱是智能体执行技能脚本的隔离环境。一个空间可以添加多份配置(Docker、E2B、CubeSandbox),每个智能体选择一份;未选择时不会执行技能脚本。',+ editorDescription: '配置空间运行环境,Docker、CubeSandbox 和 E2B 使用同一套管理流程。',stepConnection: '连接',stepTemplate: '模板',stepRuntime: '运行配置',@@ -4941,7 +4941,6 @@ export default {cube: '适合私有化或内网部署的自建 MicroVM 集群',e2b: 'E2B 托管服务或兼容 E2B 的集群',docker: '在本机 Docker 上为每个会话保留一个长驻容器,脚本和文件都落在同一容器里',- local: '直接在 WeKnora 服务进程所在环境执行脚本',},addConfig: '添加沙箱',viewClusterGuide: '集群搭建指南',@@ -4994,7 +4993,6 @@ export default {weknoraTemplateTitle: 'WeKnora 标准模板',weknoraDockerImage: 'WeKnora 标准镜像',weknoraDockerImageHint: '每次会话独占一个长驻容器,脚本、shell 命令与文件都在同一个容器内,会话结束或空闲超时后回收。',- localRuntimeWarning: '本地进程会直接在 WeKnora 服务器上执行技能脚本,不具备容器或 MicroVM 隔离。仅建议在可信的开发空间使用。',weknoraTemplateOverview: 'WeKnora 负责提供标准运行环境。连接集群后会自动发现模板,缺少标准模板时自动创建。',weknoraTemplateDescription: '包含 WeKnora 技能所需的 Python、Node.js、CLI 工具、工作目录和非 root 执行用户。',recommendedTag: '推荐',@@ -5007,7 +5005,6 @@ export default {cardEnvVars: '{count} 个环境变量',cardPrivateEndpoints: '允许访问私网',imageNotConfigured: '未配置镜像',- localRuntimeSummary: 'WeKnora 服务器本地进程',templateApplied: '已使用',refreshTemplates: '刷新模板',templateSelectHelp: '模板由当前集群实时返回,保存时仅记录模板 ID,无需手工复制。',@@ -5126,12 +5123,10 @@ export default {skipReasons: {needs_deep_check: '需完整验证',control_plane_unreachable: '控制面不可达,已跳过',- environment_unavailable: '运行环境不可用,已跳过',sandbox_not_created: '沙箱未创建,已跳过',sandbox_exec_failed: '沙箱内执行失败,已跳过',},checks: {- environment_available: '运行环境可用性',client_build: '客户端构建',api_url_reachable: '端点可达性',credential_valid: '凭据有效性',diff --git a/frontend/src/views/settings/SandboxSettings.vue b/frontend/src/views/settings/SandboxSettings.vueindex df08020b8..d25977b29 100644--- a/frontend/src/views/settings/SandboxSettings.vue+++ b/frontend/src/views/settings/SandboxSettings.vue@@ -266,8 +266,8 @@ const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)const isLegacyRecord = (record: SandboxConfigRecord) => !isNamedSandboxBackend(record.sandbox_type)-// Skills are baked into the snapshot image. Local configs have no skills-// step, so their cards stay a connection summary.+// Skills are baked into the snapshot image. Legacy configs (removed backends)+// have no skills step, so their cards stay a connection summary.function supportsSkills(record: SandboxConfigRecord) {return record.sandbox_type === 'cube' || record.sandbox_type === 'e2b' || record.sandbox_type === 'docker'}@@ -401,15 +401,12 @@ function openCard(record: SandboxConfigRecord) {openEdit(record)}-// What this config actually points at: the remote host, the container image, or-// the local runtime. Two configs of the same backend are told apart by it.+// What this config actually points at: the remote host or the container image.+// Two configs of the same backend are told apart by it.function targetSummary(record: SandboxConfigRecord): string {if (record.sandbox_type === 'docker') {return record.config?.docker?.image || ''}- if (record.sandbox_type === 'local') {- return t('settings.sandbox.localRuntimeSummary')- }return endpointHost(record)}diff --git a/internal/agent/skills/manager.go b/internal/agent/skills/manager.goindex 4e99fa03d..d7cb77973 100644--- a/internal/agent/skills/manager.go+++ b/internal/agent/skills/manager.go@@ -309,8 +309,7 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin// 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.+ // absent, directories are materialised during script execution.fileStore := sessionFileStoreFromManager(m.sandboxMgr)if fileStore != nil {env[sessionInputEnvVar] = sandbox.SessionInputRootdiff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.goindex b0a3659c8..997684cae 100644--- a/internal/agent/tools/definitions.go+++ b/internal/agent/tools/definitions.go@@ -33,8 +33,7 @@ const (// ToolShellExec lets the LLM execute ad-hoc shell commands inside the// current session's sandbox (dependency installs, environment probing).// Registered only when the resolved backend advertises the session shell- // capability — every session-scoped backend does (Cube, E2B, Docker); the- // Local backend does not, so ad-hoc commands never reach the host.+ // capability (Cube, E2B, Docker). The command never runs on the WeKnora host.ToolShellExec = "shell_exec"// Wiki-related tools (only available when wiki KBs are in scope)ToolWikiReadPage = "wiki_read_page"diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.goindex 80fe95c41..231b9f838 100644--- a/internal/agent/tools/shell_exec.go+++ b/internal/agent/tools/shell_exec.go@@ -7,10 +7,9 @@//// 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-sandbox capability: registration is feature-gated on the+// sandbox backend exposing SandboxCommandExecutor (Cube, E2B, Docker).+// 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.@@ -184,8 +183,8 @@ var shellExecTool = BaseTool{- 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.`,+- Only available when the session sandbox advertises a command executor+ (Cube, E2B, Docker). The command never runs on the WeKnora host.`,schema: utils.GenerateSchema[ShellExecInput](),}diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 5cc2a3dd3..26e1ecc85 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -424,10 +424,9 @@ func (s *agentService) initializeSkillsManager(// 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.+ // manager advertising a SessionFileStore capability. A manager that+ // cannot honour that capability returns nil so we never surface+ // tenant-isolated tools against a backend that cannot isolate them.//// They follow SkillsEnabled for the same reason the skill tools do:// the installer agent is here only for the shell it needs to install@@ -519,8 +518,8 @@ func (s *agentService) readSkillBundle(// entitled to.//// shell_exec is a remote-only capability: the capability accessors yield nil-// for stateless backends and for a SessionBoundManager that fell back to-// LocalSandbox, so the same check works for every provider.+// for backends that cannot run session-scoped shell, so the same check works+// for every provider.//// The skill installer agent gets the install-mode variant, which runs as root// and may work inside the skills image root — it exists to installdiff --git a/internal/application/service/agent_service_shell_test.go b/internal/application/service/agent_service_shell_test.goindex 74b226330..ba10ba1bf 100644--- a/internal/application/service/agent_service_shell_test.go+++ b/internal/application/service/agent_service_shell_test.go@@ -49,9 +49,9 @@ func (s *stubShellExecutor) ExecShellCommand(}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}+ // Managers that don't implement SessionCapabilityProvider (Disabled+ // DefaultManager) must never surface shell_exec.+ nonCapable := &capableManager{typ: sandbox.SandboxTypeDisabled}assert.Nil(t, sessionSandboxShellExecutor(nonCapable))assert.Nil(t, sessionSandboxFileStore(nonCapable))assert.Nil(t, sessionSandboxShellExecutor(nil))@@ -59,8 +59,7 @@ func TestSessionSandboxShellExecutorReturnsNilWithoutCapability(t *testing.T) {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.+ // honour them 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))diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex df011cb2a..d7d07fce3 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -672,9 +672,9 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {// the configured sandbox backend supports session-scoped instances.//// Only SessionBoundManager implements the DestroySession method, which every-// session-scoped backend resolves to (Cube, E2B, Docker). For Local/Disabled-// the type assertion fails and the call is a no-op — those backends are-// stateless per Execute and hold no resources keyed on session ID.+// session-scoped backend resolves to (Cube, E2B, Docker). For Disabled+// the type assertion fails and the call is a no-op — that backend holds no+// resources keyed on session ID.//// Errors are logged but never propagated: sandbox teardown must not block// session deletion. Call this while the session row is still live so thediff --git a/internal/application/service/session_attachment_staging.go b/internal/application/service/session_attachment_staging.goindex 26cb380c4..193320c06 100644--- a/internal/application/service/session_attachment_staging.go+++ b/internal/application/service/session_attachment_staging.go@@ -71,8 +71,8 @@ type sessionAttachmentStager interface {//// Callers must gate staging on this rather than on the process-wide manager: a// different workspace configs expose different capabilities. Remote backends-// need attachment staging; the stateless Local backend does not advertise a-// session filesystem at all.+// need attachment staging; backends that do not advertise a session+// filesystem skip staging entirely.func (s *agentService) sessionSandboxInputStore(ctx context.Context,sessionID string,diff --git a/internal/application/service/session_attachment_staging_test.go b/internal/application/service/session_attachment_staging_test.goindex 9b63d1aea..dd2910168 100644--- a/internal/application/service/session_attachment_staging_test.go+++ b/internal/application/service/session_attachment_staging_test.go@@ -52,7 +52,7 @@ type stagingSandboxManager struct {removes []string// disableFiles lets a test simulate a manager that advertises no- // session filesystem capability (e.g. Local fallback engaged).+ // session filesystem capability.disableFiles bool}@@ -151,10 +151,10 @@ func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {func TestStageSessionAttachmentsSkipsWhenNoFilesystemCapability(t *testing.T) {// disableFiles=true simulates any manager without a session filesystem- // capability (Local/Docker/Disabled DefaultManager, or a- // SessionBoundManager whose remote provider fell back to Local).+ // capability (Disabled DefaultManager, or a manager whose+ // SessionFileStore accessor returns nil).manager := &stagingSandboxManager{- sandboxType: sandbox.SandboxTypeLocal,+ sandboxType: sandbox.SandboxTypeDisabled,disableFiles: true,}service := &agentService{sandboxMgr: manager, fileService: &stagingFileService{}}diff --git a/internal/application/service/session_sandbox_gating_test.go b/internal/application/service/session_sandbox_gating_test.goindex e3f61a84a..86ee210ce 100644--- a/internal/application/service/session_sandbox_gating_test.go+++ b/internal/application/service/session_sandbox_gating_test.go@@ -11,16 +11,16 @@ import ()// 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+// deployment default stays disabled. 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) {// The deployment default advertises no session filesystem, standing in for- // docker/local/disabled.+ // a disabled process-wide manager.deploymentDefault := &stagingSandboxManager{- sandboxType: sandbox.SandboxTypeLocal,+ sandboxType: sandbox.SandboxTypeDisabled,disableFiles: true,}// The workspace's named config does advertise one.@@ -42,7 +42,7 @@ func TestSessionSandboxInputStoreUsesNamedConfigNotDeploymentDefault(t *testing.// backend without a session filesystem must not stage anything.func TestSessionSandboxInputStoreSkipsWhenDeploymentDefaultHasNoFilesystem(t *testing.T) {deploymentDefault := &stagingSandboxManager{- sandboxType: sandbox.SandboxTypeLocal,+ sandboxType: sandbox.SandboxTypeDisabled,disableFiles: true,}svc := &agentService{diff --git a/internal/application/service/session_sandbox_pin.go b/internal/application/service/session_sandbox_pin.goindex 50f7e24ef..3321f0af8 100644--- a/internal/application/service/session_sandbox_pin.go+++ b/internal/application/service/session_sandbox_pin.go@@ -139,8 +139,8 @@ func (p *SessionSandboxPinner) Clear(ctx context.Context, sessionID string) erroUpdate("sandbox_config_id", nil).Error}-// resolveSandboxForExecution resolves before pinning so stateless workspace-// backends (docker/local) never leave a permanent session pin. Remote backends+// resolveSandboxForExecution resolves before pinning so non-remote workspace+// backends never leave a permanent session pin. Remote backends// pin before their first Create; concurrent callers adopt and re-resolve the// winning config before executing anything.func resolveSandboxForExecution(diff --git a/internal/application/service/session_sandbox_pin_test.go b/internal/application/service/session_sandbox_pin_test.goindex cd94a43da..31f1a4f44 100644--- a/internal/application/service/session_sandbox_pin_test.go+++ b/internal/application/service/session_sandbox_pin_test.go@@ -149,7 +149,7 @@ func TestSoftDeleteHidesSandboxPin(t *testing.T) {func TestResolveSandboxForExecutionDoesNotPinStatelessBackend(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))- want := &pinTestManager{typ: sandbox.SandboxTypeLocal}+ want := &pinTestManager{typ: sandbox.SandboxTypeDisabled}got, configID, err := resolveSandboxForExecution(context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,@@ -161,7 +161,7 @@ func TestResolveSandboxForExecutionDoesNotPinStatelessBackend(t *testing.T) {require.Equal(t, "cfg-local", configID)pinned, err := pinner.Read(context.Background(), "s-1")require.NoError(t, err)- require.Empty(t, pinned, "local and Docker executions must not leave a session binding")+ require.Empty(t, pinned, "disabled backends must not leave a session binding")}func TestResolveSandboxForExecutionPinsRemoteBackend(t *testing.T) {diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.goindex 54896eaa4..d026798b7 100644--- a/internal/application/service/tenant_sandbox_config.go+++ b/internal/application/service/tenant_sandbox_config.go@@ -171,7 +171,7 @@ var ErrSandboxConfigNameRequired = stderrors.New("sandbox config name is require// ErrNamedSandboxBackendUnsupported marks a sandbox type that cannot be stored// as a user-facing named backend config.var ErrNamedSandboxBackendUnsupported = stderrors.New(- "named sandbox configs only support cube, e2b, docker and local backends",+ "named sandbox configs only support cube, e2b and docker backends",)// ErrSkillSnapshotBlocksTemplateChange is returned when this config already@@ -468,11 +468,11 @@ func (s *TenantSandboxConfigService) SetWorkspaceScriptsDisabled(func (s *TenantSandboxConfigService) Create(ctx context.Context, tenantID uint64, in CreateSandboxConfigInput,) (*types.TenantSandboxConfigEntity, error) {- merged, err := SanitizeSandboxConfig(in.Config, nil)- if err != nil {+ if err := validateNamedSandboxBackend(in.Config); err != nil {return nil, err}- if err := validateNamedSandboxBackend(merged); err != nil {+ merged, err := SanitizeSandboxConfig(in.Config, nil)+ if err != nil {return nil, err}name := strings.TrimSpace(in.Name)@@ -953,6 +953,11 @@ func (s *TenantSandboxConfigService) Update(if types.IsSandboxWorkspacePolicyRow(entity) {return nil, apperrors.NewBadRequestError("workspace policy cannot be edited here")}+ if in.Config != nil && strings.TrimSpace(in.Config.SandboxType) != "" {+ if err := validateNamedSandboxBackend(in.Config); err != nil {+ return nil, err+ }+ }merged, err := SanitizeSandboxConfig(in.Config, entity.Config)if err != nil {return nil, errdiff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.goindex 89ef731b1..9bb3d4021 100644--- a/internal/application/service/tenant_sandbox_config_test.go+++ b/internal/application/service/tenant_sandbox_config_test.go@@ -1427,7 +1427,10 @@ func TestSanitizeSandboxConfigRefusesSecretsWithoutAESKey(t *testing.T) {require.Error(t, err)// A config without secrets is still allowed in that deployment.- _, err = SanitizeSandboxConfig(&types.TenantSandboxConfig{SandboxType: "local"}, nil)+ _, err = SanitizeSandboxConfig(&types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{Image: "weknora:test"},+ }, nil)require.NoError(t, err)}@@ -1437,17 +1440,10 @@ func TestSandboxesStillLiveErrorSupportsErrorsIs(t *testing.T) {require.True(t, stderrors.Is(err, ErrSandboxesStillLive))}-func TestCreateAcceptsStatelessNamedSandboxBackends(t *testing.T) {+func TestCreateAcceptsDockerNamedSandboxBackend(t *testing.T) {repo := &fakeConfigRepo{}svc := newTestConfigService(t, repo, nil, stubAgentRepo{})- local, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{- Name: "local-dev",- Config: &types.TenantSandboxConfig{SandboxType: "local"},- })- require.NoError(t, err)- require.Equal(t, "local", local.SandboxType)-docker, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{Name: "docker-dev",Config: &types.TenantSandboxConfig{@@ -1459,6 +1455,16 @@ func TestCreateAcceptsStatelessNamedSandboxBackends(t *testing.T) {require.Equal(t, "docker", docker.SandboxType)}+func TestCreateRejectsRemovedLocalBackend(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 TestCreateRejectsDockerWithoutImage(t *testing.T) {svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})@@ -1546,8 +1552,11 @@ func TestDeleteWithForceProceedsAndRecordsThePartialSuccess(t *testing.T) {func TestDeleteMarksBuildingSnapshotsWhenProviderHasNoSnapshotClient(t *testing.T) {repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{- ID: "cfg-a", TenantID: 7, Name: "local", SandboxType: "local",- Config: &types.TenantSandboxConfig{SandboxType: "local"},+ ID: "cfg-a", TenantID: 7, Name: "docker", SandboxType: "docker",+ Config: &types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{Image: "weknora:test"},+ },}}skills := &deleteSkillStore{snapshots: []*types.TenantSkillSnapshotEntity{{diff --git a/internal/application/service/tenant_skill_effective_test.go b/internal/application/service/tenant_skill_effective_test.goindex e2db10257..ecdba59c8 100644--- a/internal/application/service/tenant_skill_effective_test.go+++ b/internal/application/service/tenant_skill_effective_test.go@@ -101,8 +101,8 @@ func TestEffectiveTenantSkillsInjectsNothingWhenTheFingerprintDisagrees(t *testifunc TestEffectiveTenantSkillsInjectsNothingWhenTheBackendCannotSnapshot(t *testing.T) {fx := newEffectiveFixture(t)- fx.configs.entity.SandboxType = "local"- fx.configs.entity.Config.SandboxType = "local"+ fx.configs.entity.SandboxType = "disabled"+ fx.configs.entity.Config.SandboxType = "disabled"require.Empty(t, fx.derive(context.Background()))}diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.goindex 1f2218025..0fc0c7737 100644--- a/internal/application/service/tenant_skill_install.go+++ b/internal/application/service/tenant_skill_install.go@@ -816,8 +816,8 @@ func describeExecFailure(res *sandbox.ExecuteResult) string {// installExecutor resolves the one executor every command of an install runs// through. It goes through the capability accessor rather than a bare type-// assertion so a manager that fell back to LocalSandbox reports no capability-// instead of running the install on the WeKnora host.+// assertion so a manager that cannot run install-mode shell reports no+// capability instead of attempting the install on the WeKnora host.func installExecutor(mgr sandbox.Manager) (sandbox.SessionInstallShellExecutor, error) {executor := sessionSandboxInstallShellExecutor(mgr)if executor == nil {@@ -1761,8 +1761,8 @@ func skillOwnerFingerprint(cfg *types.TenantSandboxConfig) string {// configSandboxInvalidator is the narrow capability marking bound sandboxes// needs. It is reached by type assertion rather than declared on Manager-// because only the session-bound remote manager owns bindings to mark: a local-// or disabled backend has none, and for those doing nothing is correct.+// because only the session-bound remote manager owns bindings to mark: a+// disabled backend has none, and for that doing nothing is correct.type configSandboxInvalidator interface {InvalidateConfigSandboxes(ctx context.Context, tenantID uint64, configID string) (int, error)}diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.goindex 44e949a43..10bfa1744 100644--- a/internal/application/service/tenant_skill_install_test.go+++ b/internal/application/service/tenant_skill_install_test.go@@ -756,9 +756,10 @@ func TestSwitchImagePointerRefusesAnUnusableFingerprint(t *testing.T) {fx := newInstallFixture(t)// A config whose provider cannot snapshot produces no fingerprint,// and a pointer with an empty fingerprint is discarded at session start.- fx.configRepo.entity.SandboxType = "local"- fx.configRepo.entity.Config.SandboxType = "local"+ fx.configRepo.entity.SandboxType = "docker"+ fx.configRepo.entity.Config.SandboxType = "docker"fx.configRepo.entity.Config.E2B = nil+ fx.configRepo.entity.Config.Docker = nilerr := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)diff --git a/internal/container/sandbox.go b/internal/container/sandbox.goindex 115935dee..d1e203d10 100644--- a/internal/container/sandbox.go+++ b/internal/container/sandbox.go@@ -101,7 +101,6 @@ func (c *repositorySessionExistenceChecker) SessionExists(func buildGlobalSandboxConfig() *sandbox.Config {cfg := sandbox.DefaultConfig()cfg.Type = sandbox.SandboxTypeDisabled- cfg.FallbackEnabled = falsereturn cfg}@@ -117,8 +116,7 @@ func newTenantSandboxResolver(ctx := context.Background()// Tenants may configure any supported backend regardless of process startup- // mode. Remote configs use this binding store for session persistence;- // Docker and Local configs remain stateless.+ // mode. Remote configs use this binding store for session persistence.store, storeKind, err := selectSessionBindingStore(redisClient, true)if err != nil {logger.Warnf(ctx,diff --git a/internal/handler/sandbox_check.go b/internal/handler/sandbox_check.goindex 8f5936ed0..6158b84ba 100644--- a/internal/handler/sandbox_check.go+++ b/internal/handler/sandbox_check.go@@ -5,8 +5,6 @@ import (stderrors "errors""fmt""net/http"- "os"- "path/filepath""strings""time"@@ -56,7 +54,6 @@ const (skipReasonNeedsDeepCheck = "needs_deep_check"// An earlier probe failed and this one cannot be reached without it.skipReasonControlPlaneUnreachable = "control_plane_unreachable"- skipReasonEnvironmentUnavailable = "environment_unavailable"skipReasonSandboxNotCreated = "sandbox_not_created"skipReasonSandboxExecFailed = "sandbox_exec_failed")@@ -144,12 +141,6 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {}result := &SandboxCheckResponse{OK: true, Provider: string(effective.Type)}- if effective.Type == sandbox.SandboxTypeLocal {- h.runStatelessSandboxCheck(ctx, effective, req.Deep, result)- c.JSON(http.StatusOK, gin.H{"success": true, "data": result})- return- }-client, err := sandbox.NewRemoteClientForCheck(effective)if err != nil {result.add("client_build", false, err.Error(), 0)@@ -224,86 +215,6 @@ func sandboxConnectionCheckConfig(cfg *types.TenantSandboxConfig) *types.TenantSreturn ©}-func (h *SystemHandler) runStatelessSandboxCheck(- ctx context.Context,- cfg *sandbox.Config,- deep bool,- result *SandboxCheckResponse,-) {- cfg.FallbackEnabled = false- mgr, err := sandbox.NewManager(cfg)- if err != nil {- result.add("environment_available", false, err.Error(), 0)- result.skip("sandbox_exec", skipReasonEnvironmentUnavailable)- return- }- defer func() { _ = mgr.Cleanup(context.WithoutCancel(ctx)) }()- active := mgr.GetSandbox()- available := active != nil && active.IsAvailable(ctx)- result.add("environment_available", available, "", 0)- if !available || !deep {- reason := skipReasonNeedsDeepCheck- if !available {- reason = skipReasonEnvironmentUnavailable- }- result.skip("sandbox_exec", reason)- return- }-- dir, err := createProbeStagingDir()- if err != nil {- result.add("sandbox_exec", false, err.Error(), 0)- return- }- defer func() { _ = os.RemoveAll(dir) }()- path := filepath.Join(dir, "check.sh")- const script = "#!/bin/sh\nprintf 'weknora-ok\\n'\n"- if err := os.WriteFile(path, []byte(script), 0o644); err != nil {- result.add("sandbox_exec", false, err.Error(), 0)- return- }- if err := os.Chmod(path, 0o644); err != nil {- result.add("sandbox_exec", false, err.Error(), 0)- return- }-- start := time.Now()- execResult, err := mgr.Execute(ctx, &sandbox.ExecuteConfig{- Script: path,- ScriptContent: script,- Timeout: 90 * time.Second,- })- latency := time.Since(start).Milliseconds()- if err != nil {- result.add("sandbox_exec", false, err.Error(), latency)- return- }- if execResult == nil || !strings.Contains(execResult.Stdout, "weknora-ok") {- if execResult == nil {- result.add("sandbox_exec", false, "沙箱没有返回执行结果", latency)- return- }- result.add("sandbox_exec", false, describeProbeMismatch(- execResult.ExitCode, execResult.Killed,- execResult.Stdout, execResult.Stderr, execResult.Error,- ), latency)- return- }- result.add("sandbox_exec", true, "", latency)-}--// createProbeStagingDir makes the directory the local probe script is written-// to. It stays next to the real skill scripts under the process working-// directory and only falls back to the temp dir when that is not writable.-func createProbeStagingDir() (string, error) {- if wd, err := os.Getwd(); err == nil {- if dir, err := os.MkdirTemp(wd, ".weknora-sandbox-check-*"); err == nil {- return dir, nil- }- }- return os.MkdirTemp("", "weknora-sandbox-check-*")-}-// describeProbeMismatch reports why the probe script did not print its marker.// "命令输出与预期不符" on its own hides the exit code and the stderr line that// normally name the actual problem — a missing interpreter, an image entrypointdiff --git a/internal/handler/sandbox_check_test.go b/internal/handler/sandbox_check_test.goindex 1e0d3039b..5c2b5227a 100644--- a/internal/handler/sandbox_check_test.go+++ b/internal/handler/sandbox_check_test.go@@ -1,7 +1,6 @@package handlerimport (- "context""testing""github.com/stretchr/testify/require"@@ -32,19 +31,10 @@ func TestSandboxCheckReasonDockerUnavailableIncludesHost(t *testing.T) {require.Contains(t, msg, "docker context")}-func TestRunStatelessSandboxCheckLocal(t *testing.T) {- cfg := sandbox.DefaultConfig()- cfg.Type = sandbox.SandboxTypeLocal- result := &SandboxCheckResponse{OK: true, Provider: string(cfg.Type)}-- (&SystemHandler{}).runStatelessSandboxCheck(context.Background(), cfg, true, result)-- require.True(t, result.OK)- require.Len(t, result.Checks, 2)- require.Equal(t, "environment_available", result.Checks[0].Name)- require.NotNil(t, result.Checks[0].OK)- require.True(t, *result.Checks[0].OK)- require.Equal(t, "sandbox_exec", result.Checks[1].Name)- require.NotNil(t, result.Checks[1].OK)- require.True(t, *result.Checks[1].OK)+func TestRunStatelessSandboxCheckRemovedWithLocalBackend(t *testing.T) {+ incoming := &types.TenantSandboxConfig{SandboxType: "local"}++ _, err := sandbox.ResolveEffectiveConfig(incoming, sandbox.DefaultConfig())++ require.ErrorIs(t, err, sandbox.ErrUnsupportedSandboxType)}diff --git a/internal/sandbox/capabilities.go b/internal/sandbox/capabilities.goindex 4f5f7d3f2..00a80e21d 100644--- a/internal/sandbox/capabilities.go+++ b/internal/sandbox/capabilities.go@@ -1,20 +1,15 @@// 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+// E2B, Docker) 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.+// that couples them to a specific backend.//// 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.+// current runtime configuration cannot honour that capability.package sandboximport (@@ -23,9 +18,8 @@ import ()// SessionShellExecutor executes ad-hoc shell commands inside a session--// scoped remote sandbox. Local backends do not implement it; a-// SessionBoundManager only surfaces it while the remote backend is active-// (Cube, E2B, or Docker).+// scoped remote sandbox. SessionBoundManager surfaces it while Cube, E2B,+// or Docker is active.type SessionShellExecutor interface {ExecShellCommand(ctx context.Context,@@ -73,9 +67,8 @@ type SessionFileStore interface {// 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.+// runtime configuration cannot support that capability. Application code+// should gate feature registration on non-nil accessor returns.type SessionCapabilityProvider interface {SessionShellExecutor() SessionShellExecutorSessionFileStore() SessionFileStorediff --git a/internal/sandbox/config_identity_test.go b/internal/sandbox/config_identity_test.goindex 867016c8e..8d26c0849 100644--- a/internal/sandbox/config_identity_test.go+++ b/internal/sandbox/config_identity_test.go@@ -61,12 +61,12 @@ func TestIdentityOfReadsOnlyActiveProvider(t *testing.T) {// 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) {+func TestIdentityOfDockerWithoutHostCarriesProviderOnly(t *testing.T) {docker := IdentityOf(&types.TenantSandboxConfig{SandboxType: "docker"})- local := IdentityOf(&types.TenantSandboxConfig{SandboxType: "local"})+ cube := IdentityOf(&types.TenantSandboxConfig{SandboxType: "cube"})require.Equal(t, SandboxIdentity{Provider: "docker"}, docker)- require.NotEqual(t, docker, local)+ require.NotEqual(t, docker, cube)}// A nil config must not panic: Update compares against it when creating.diff --git a/internal/sandbox/config_required.go b/internal/sandbox/config_required.goindex 36653804a..540331533 100644--- a/internal/sandbox/config_required.go+++ b/internal/sandbox/config_required.go@@ -30,7 +30,7 @@ var ErrSandboxConfigIncomplete = errors.New("sandbox: config is missing required// MissingRequiredFields lists the fields cfg fails to supply for its own// provider, named after the JSON keys the API and the settings form use so the-// message can be surfaced without translation. Local and disabled hold no+// message can be surfaced without translation. Disabled holds no// backend-specific values; Docker must explicitly name its image.func MissingRequiredFields(cfg *Config) []string {if cfg == nil {diff --git a/internal/sandbox/cube_integration_test.go b/internal/sandbox/cube_integration_test.goindex 27f14f88c..b68a9f211 100644--- a/internal/sandbox/cube_integration_test.go+++ b/internal/sandbox/cube_integration_test.go@@ -53,7 +53,6 @@ func integrationConfig(t *testing.T) *Config {t.Helper()cfg := DefaultConfig()cfg.Type = SandboxTypeCube- cfg.FallbackEnabled = falseif v := strings.TrimSpace(os.Getenv("CUBE_API_URL")); v != "" {cfg.CubeAPIURL = v@@ -419,7 +418,7 @@ func TestIntegrationCubeClient_FilesystemOps(t *testing.T) {// TestIntegrationRemoteSandbox_EphemeralExecute exercises the empty-SessionID// path through SessionBoundManager: the manager allocates a fresh MicroVM,-// runs the script, and tears it down — same wire behaviour Docker/Local+// runs the script, and tears it down — same wire behaviour Docker// sandboxes present per Execute.func TestIntegrationRemoteSandbox_EphemeralExecute(t *testing.T) {mgr := newIntegrationManager(t)diff --git a/internal/sandbox/docker_integration_test.go b/internal/sandbox/docker_integration_test.goindex 6660cecf9..7575de36a 100644--- a/internal/sandbox/docker_integration_test.go+++ b/internal/sandbox/docker_integration_test.go@@ -43,7 +43,6 @@ func dockerIntegrationConfig(t *testing.T) *Config {}cfg := DefaultConfig()cfg.Type = SandboxTypeDocker- cfg.FallbackEnabled = falsecfg.DockerImage = imagecfg.DockerHost = strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST"))cfg.DefaultTimeout = 2 * time.Minutediff --git a/internal/sandbox/e2b_compatible_integration_test.go b/internal/sandbox/e2b_compatible_integration_test.goindex 3272ddcbe..0919e695f 100644--- a/internal/sandbox/e2b_compatible_integration_test.go+++ b/internal/sandbox/e2b_compatible_integration_test.go@@ -247,7 +247,6 @@ func e2bCompatibleConfig(t *testing.T) *Config {cfg := DefaultConfig()cfg.Type = SandboxTypeE2B- cfg.FallbackEnabled = falsecfg.AllowPrivateEndpoints = truecfg.E2BAPIKey = apiKeycfg.E2BTemplate = templatediff --git a/internal/sandbox/e2b_integration_test.go b/internal/sandbox/e2b_integration_test.goindex 6c27d50a8..6c575529d 100644--- a/internal/sandbox/e2b_integration_test.go+++ b/internal/sandbox/e2b_integration_test.go@@ -210,7 +210,6 @@ func e2bIntegrationConfig(t *testing.T) *Config {cfg := DefaultConfig()cfg.Type = SandboxTypeE2B- cfg.FallbackEnabled = falsecfg.E2BAPIKey = apiKeycfg.E2BAPIURL = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_API_URL"))cfg.E2BSandboxDomain = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_SANDBOX_DOMAIN"))diff --git a/internal/sandbox/local.go b/internal/sandbox/local.godeleted file mode 100644index 80a4591e4..000000000--- a/internal/sandbox/local.go+++ /dev/null@@ -1,249 +0,0 @@-package sandbox--import (- "bytes"- "context"- "fmt"- "os"- "os/exec"- "path/filepath"- "strings"- "time"-)--// LocalSandbox implements the Sandbox interface using local process isolation-// This is a fallback option when Docker is not available-// It provides basic isolation through:-// - Command whitelist validation-// - Working directory restriction-// - Timeout enforcement-// - Environment variable filtering-type LocalSandbox struct {- config *Config-}--// NewLocalSandbox creates a new local process-based sandbox-func NewLocalSandbox(config *Config) *LocalSandbox {- if config == nil {- config = DefaultConfig()- }- return &LocalSandbox{- config: config,- }-}--// Type returns the sandbox type-func (s *LocalSandbox) Type() SandboxType {- return SandboxTypeLocal-}--// IsAvailable checks if local sandbox is available-func (s *LocalSandbox) IsAvailable(ctx context.Context) bool {- // Local sandbox is always available- return true-}--// Execute runs a script locally with basic isolation-func (s *LocalSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {- if config == nil {- return nil, ErrInvalidScript- }-- // Validate the script path- if err := s.validateScript(config.Script); err != nil {- return nil, err- }-- // Determine interpreter- interpreter := s.getInterpreter(config.Script)- if !s.isAllowedCommand(interpreter) {- return nil, fmt.Errorf("interpreter not allowed: %s", interpreter)- }-- // Set default timeout- timeout := config.Timeout- if timeout == 0 {- timeout = s.config.DefaultTimeout- }- if timeout == 0 {- timeout = DefaultTimeout- }-- // Create context with timeout- execCtx, cancel := context.WithTimeout(ctx, timeout)- defer cancel()-- // Build command- args := append([]string{config.Script}, config.Args...)- cmd := exec.CommandContext(execCtx, interpreter, args...)-- // Set working directory- if config.WorkDir != "" {- cmd.Dir = config.WorkDir- } else {- cmd.Dir = filepath.Dir(config.Script)- }-- // Setup minimal environment- cmd.Env = s.buildEnvironment(config.Env)-- // Setup process group for cleanup- setupProcessGroup(cmd)-- var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr-- if config.Stdin != "" {- cmd.Stdin = strings.NewReader(config.Stdin)- }-- startTime := time.Now()- err := cmd.Run()- duration := time.Since(startTime)-- result := &ExecuteResult{- Stdout: stdout.String(),- Stderr: stderr.String(),- Duration: duration,- }-- if err != nil {- if execCtx.Err() == context.DeadlineExceeded {- // Kill the process group- if cmd.Process != nil {- killProcessGroup(cmd)- }- result.Killed = true- result.Error = ErrTimeout.Error()- result.ExitCode = -1- } else if exitErr, ok := err.(*exec.ExitError); ok {- result.ExitCode = exitErr.ExitCode()- } else {- result.Error = err.Error()- result.ExitCode = -1- }- }-- return result, nil-}--// validateScript checks if the script path is valid and safe-func (s *LocalSandbox) validateScript(scriptPath string) error {- // Check if script exists- info, err := os.Stat(scriptPath)- if err != nil {- if os.IsNotExist(err) {- return ErrScriptNotFound- }- return fmt.Errorf("failed to access script: %w", err)- }-- if info.IsDir() {- return ErrInvalidScript- }-- // Check path is absolute- if !filepath.IsAbs(scriptPath) {- return fmt.Errorf("script path must be absolute: %s", scriptPath)- }-- // Validate against allowed paths if configured- if len(s.config.AllowedPaths) > 0 {- allowed := false- absPath, _ := filepath.Abs(scriptPath)- for _, allowedPath := range s.config.AllowedPaths {- absAllowed, _ := filepath.Abs(allowedPath)- if strings.HasPrefix(absPath, absAllowed) {- allowed = true- break- }- }- if !allowed {- return fmt.Errorf("script path not in allowed paths: %s", scriptPath)- }- }-- return nil-}--// getInterpreter returns the appropriate interpreter for a script-func (s *LocalSandbox) getInterpreter(scriptPath string) string {- ext := strings.ToLower(filepath.Ext(scriptPath))- switch ext {- case ".py":- return "python3"- case ".sh", ".bash":- return "bash"- case ".js":- return "node"- case ".rb":- return "ruby"- case ".pl":- return "perl"- case ".php":- return "php"- default:- return "sh"- }-}--// isAllowedCommand checks if a command is in the allowed list-func (s *LocalSandbox) isAllowedCommand(cmd string) bool {- if len(s.config.AllowedCommands) == 0 {- // Use default allowed commands- defaults := defaultAllowedCommands()- for _, allowed := range defaults {- if cmd == allowed {- return true- }- }- return false- }-- for _, allowed := range s.config.AllowedCommands {- if cmd == allowed {- return true- }- }- return false-}--// buildEnvironment creates a safe environment for script execution-func (s *LocalSandbox) buildEnvironment(extra map[string]string) []string {- // Start with minimal environment- env := []string{- "PATH=/usr/local/bin:/usr/bin:/bin",- "HOME=/tmp",- "LANG=en_US.UTF-8",- "LC_ALL=en_US.UTF-8",- }-- // Dangerous environment variables to exclude- dangerous := map[string]bool{- "LD_PRELOAD": true,- "LD_LIBRARY_PATH": true,- "PYTHONPATH": true,- "NODE_OPTIONS": true,- "BASH_ENV": true,- "ENV": true,- "SHELL": true,- }-- // Add extra environment variables (filtered)- for key, value := range extra {- upperKey := strings.ToUpper(key)- if dangerous[upperKey] {- continue- }- env = append(env, fmt.Sprintf("%s=%s", key, value))- }-- return env-}--// Cleanup releases any resources-func (s *LocalSandbox) Cleanup(ctx context.Context) error {- // Local sandbox doesn't need cleanup- return nil-}diff --git a/internal/sandbox/local_unix.go b/internal/sandbox/local_unix.godeleted file mode 100644index ec03e6a36..000000000--- a/internal/sandbox/local_unix.go+++ /dev/null@@ -1,20 +0,0 @@-//go:build !windows--package sandbox--import (- "os/exec"- "syscall"-)--func setupProcessGroup(cmd *exec.Cmd) {- cmd.SysProcAttr = &syscall.SysProcAttr{- Setpgid: true,- }-}--func killProcessGroup(cmd *exec.Cmd) {- if cmd.Process != nil {- syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)- }-}diff --git a/internal/sandbox/local_windows.go b/internal/sandbox/local_windows.godeleted file mode 100644index 17141b0c2..000000000--- a/internal/sandbox/local_windows.go+++ /dev/null@@ -1,17 +0,0 @@-//go:build windows--package sandbox--import (- "os/exec"-)--func setupProcessGroup(cmd *exec.Cmd) {- // Windows does not support Setpgid; process groups are managed via Job Objects-}--func killProcessGroup(cmd *exec.Cmd) {- if cmd.Process != nil {- cmd.Process.Kill()- }-}diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.goindex 861ca8b64..266a2a565 100644--- a/internal/sandbox/manager.go+++ b/internal/sandbox/manager.go@@ -47,10 +47,6 @@ func (m *DefaultManager) initializeSandbox(ctx context.Context) error {m.sandbox = &disabledSandbox{}return nil- case SandboxTypeLocal:- m.sandbox = NewLocalSandbox(m.config)- return nil-case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:// Session-scoped remote backends are only reachable through// SessionBoundManager, which owns the authoritative binding.@@ -226,15 +222,13 @@ func (s *disabledSandbox) IsAvailable(ctx context.Context) bool {// dockerImage is optional; if empty, the default image is used.//// Session-scoped backends (Cube, E2B, Docker) route to SessionBoundManager,-// which keeps one persistent sandbox per SessionID; the stateless ones (Local,-// Disabled) route to DefaultManager. Both satisfy Manager.-func NewManagerFromType(sandboxType string, fallbackEnabled bool, dockerImage string) (Manager, error) {+// which keeps one persistent sandbox per SessionID; Disabled routes to+// DefaultManager. Both satisfy Manager.+func NewManagerFromType(sandboxType string, dockerImage string) (Manager, error) {var sType SandboxTypeswitch sandboxType {case "docker":sType = SandboxTypeDocker- case "local":- sType = SandboxTypeLocalcase "cube":sType = SandboxTypeCubecase "e2b":@@ -247,7 +241,6 @@ func NewManagerFromType(sandboxType string, fallbackEnabled bool, dockerImage stconfig := DefaultConfig()config.Type = sType- config.FallbackEnabled = fallbackEnabledif dockerImage != "" {config.DockerImage = dockerImage}diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.goindex dc66c4994..244fa07d4 100644--- a/internal/sandbox/remote_client.go+++ b/internal/sandbox/remote_client.go@@ -448,8 +448,8 @@ type RemoteSnapshotManager interface {}// SnapshotManagerFrom narrows a client to its snapshot capability. It returns-// false for providers that cannot snapshot (local), so callers can fall-// back to the base template instead of failing.+// false for providers that cannot snapshot, so callers can fall back to the+// base template instead of failing.//// Both signals must agree: the type assertion finds the methods, and// SupportsSnapshots is the advertised capability. A wrapper that happens todiff --git a/internal/sandbox/remote_sandbox.go b/internal/sandbox/remote_sandbox.goindex e558d4269..c7ca61914 100644--- a/internal/sandbox/remote_sandbox.go+++ b/internal/sandbox/remote_sandbox.go@@ -8,8 +8,7 @@//// - Ephemeral: one call to Execute allocates a sandbox, uploads the script,// runs it, then deletes the sandbox regardless of success. This gives-// stateless-per-call semantics for callers without a SessionID, matching-// the Local backend.+// stateless-per-call semantics for callers without a SessionID.// - Persistent (session-bound): SessionBoundManager resolves the session's// RemoteSandboxHandle through the lifecycle coordinator and hands it to// RemoteSandbox.ExecuteOnHandle. The handle stays owned by the manager;diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.goindex 4abdf6157..532b8e57d 100644--- a/internal/sandbox/sandbox.go+++ b/internal/sandbox/sandbox.go@@ -1,5 +1,5 @@// Package sandbox provides isolated execution environments for running untrusted scripts.-// It supports multiple backends including Docker containers and local process isolation.+// It supports Docker containers and remote MicroVM backends (CubeSandbox, E2B).package sandboximport (@@ -17,8 +17,6 @@ const (// backends it keeps session state between executions; unlike them it// shares the host kernel and lives on a single daemon.SandboxTypeDocker SandboxType = "docker"- // SandboxTypeLocal uses local process with restrictions- SandboxTypeLocal SandboxType = "local"// SandboxTypeCube uses Tencent CubeSandbox (E2B-compatible) MicroVM for isolation.// Like Docker and E2B it keeps session-scoped persistent sandboxes: multiple// executions bound to the same SessionID share one instance and preserve@@ -31,11 +29,11 @@ const ()// IsNamedSandboxBackendType reports whether raw can be stored as a user-facing-// named sandbox backend. Cube, E2B and Docker are session-persistent; local-// is stateless. All four share the same workspace configuration surface.+// named sandbox backend. Cube, E2B and Docker are all session-persistent and+// share the same workspace configuration surface.func IsNamedSandboxBackendType(raw string) bool {switch SandboxType(raw) {- case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker, SandboxTypeLocal:+ case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:return truedefault:return false@@ -175,9 +173,9 @@ type ExecuteConfig struct {ScriptContent string// SessionID scopes the execution to a per-session persistent sandbox.- // Honoured by every session-scoped backend (Cube, E2B, Docker); the Local- // backend ignores it. When empty, those backends fall back to an ephemeral- // (one-shot) sandbox created and torn down inside the single Execute call.+ // Honoured by Cube, E2B and Docker. When empty, those backends fall back+ // to an ephemeral (one-shot) sandbox created and torn down inside the+ // single Execute call.SessionID string// RemoteScriptPath is an absolute path to a script that already exists@@ -220,9 +218,6 @@ type Config struct {// Type is the preferred sandbox typeType SandboxType- // FallbackEnabled allows falling back to local sandbox if Docker is unavailable- FallbackEnabled bool-// DefaultTimeout is the default execution timeoutDefaultTimeout time.Duration@@ -268,12 +263,6 @@ type Config struct {// DockerHTTPTimeout bounds each Engine API call. Zero uses the default.DockerHTTPTimeout time.Duration- // AllowedCommands is the default list of allowed commands- AllowedCommands []string-- // AllowedPaths is the list of paths that can be accessed- AllowedPaths []string-// MaxMemory is the maximum memory limit in bytesMaxMemory int64@@ -351,11 +340,9 @@ type Config struct {// incomplete workspace config could silently dial localhost.func DefaultConfig() *Config {return &Config{- Type: SandboxTypeLocal,- FallbackEnabled: true,+ Type: SandboxTypeDisabled,DefaultTimeout: DefaultTimeout,DockerImage: DefaultDockerImage,- AllowedCommands: defaultAllowedCommands(),MaxMemory: DefaultMemoryLimit,MaxCPU: DefaultCPULimit,CubeSandboxTTL: DefaultCubeSandboxTTL,@@ -363,32 +350,6 @@ func DefaultConfig() *Config {}}-// defaultAllowedCommands returns the default list of safe commands-func defaultAllowedCommands() []string {- return []string{- "python",- "python3",- "node",- "bash",- "sh",- "cat",- "echo",- "head",- "tail",- "grep",- "sed",- "awk",- "sort",- "uniq",- "wc",- "cut",- "tr",- "ls",- "pwd",- "date",- }-}-// ValidateConfig validates sandbox configurationfunc ValidateConfig(config *Config) error {if config == nil {@@ -396,7 +357,7 @@ func ValidateConfig(config *Config) error {}switch config.Type {- case SandboxTypeDocker, SandboxTypeLocal, SandboxTypeCube, SandboxTypeE2B, SandboxTypeDisabled:+ case SandboxTypeDocker, SandboxTypeCube, SandboxTypeE2B, SandboxTypeDisabled:// Valid typesdefault:return errors.New("invalid sandbox type")diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.goindex 60c424a98..7ae9392ff 100644--- a/internal/sandbox/sandbox_test.go+++ b/internal/sandbox/sandbox_test.go@@ -2,8 +2,6 @@ package sandboximport ("context"- "os"- "path/filepath""testing""time")@@ -11,17 +9,13 @@ import (func TestDefaultConfig(t *testing.T) {config := DefaultConfig()- if config.Type != SandboxTypeLocal {- t.Errorf("Expected default type to be local, got %s", config.Type)+ if config.Type != SandboxTypeDisabled {+ t.Errorf("Expected default type to be disabled, got %s", config.Type)}if config.DefaultTimeout != DefaultTimeout {t.Errorf("Expected default timeout %v, got %v", DefaultTimeout, config.DefaultTimeout)}-- if !config.FallbackEnabled {- t.Error("Expected fallback to be enabled by default")- }}func TestValidateConfig(t *testing.T) {@@ -36,9 +30,9 @@ func TestValidateConfig(t *testing.T) {wantErr: true,},{- name: "valid config",+ name: "valid disabled config",config: &Config{- Type: SandboxTypeLocal,+ Type: SandboxTypeDisabled,DefaultTimeout: 30 * time.Second,},wantErr: false,@@ -50,10 +44,17 @@ func TestValidateConfig(t *testing.T) {},wantErr: true,},+ {+ name: "removed local type",+ config: &Config{+ Type: "local",+ },+ wantErr: true,+ },{name: "negative timeout",config: &Config{- Type: SandboxTypeLocal,+ Type: SandboxTypeDisabled,DefaultTimeout: -1 * time.Second,},wantErr: true,@@ -70,143 +71,17 @@ func TestValidateConfig(t *testing.T) {}}-func TestLocalSandboxExecute(t *testing.T) {- // Create a temporary script- tmpDir, err := os.MkdirTemp("", "sandbox-test")- if err != nil {- t.Fatalf("Failed to create temp dir: %v", err)- }- defer os.RemoveAll(tmpDir)-- // Write a simple test script- scriptPath := filepath.Join(tmpDir, "test.sh")- scriptContent := `#!/bin/bash-echo "Hello from sandbox"-echo "Args: $@"-`- if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {- t.Fatalf("Failed to write script: %v", err)- }-- // Create local sandbox- config := DefaultConfig()- config.Type = SandboxTypeLocal- sandbox := NewLocalSandbox(config)-- // Check availability- ctx := context.Background()- if !sandbox.IsAvailable(ctx) {- t.Error("Local sandbox should always be available")- }-- // Execute script- result, err := sandbox.Execute(ctx, &ExecuteConfig{- Script: scriptPath,- Args: []string{"arg1", "arg2"},- Timeout: 10 * time.Second,- })-- if err != nil {- t.Fatalf("Failed to execute script: %v", err)- }-- if result.ExitCode != 0 {- t.Errorf("Expected exit code 0, got %d", result.ExitCode)- }-- if result.Stdout == "" {- t.Error("Expected stdout to be non-empty")- }-- t.Logf("Script output: %s", result.Stdout)- t.Logf("Duration: %v", result.Duration)-}--func TestManagerMergesWorkspaceEnvironmentVariables(t *testing.T) {- tmpDir := t.TempDir()- scriptPath := filepath.Join(tmpDir, "env.sh")- scriptContent := "#!/bin/sh\nprintf '%s|%s' \"$WORKSPACE_VALUE\" \"$OVERRIDE_VALUE\"\n"- if err := os.WriteFile(scriptPath, []byte(scriptContent), 0o755); err != nil {- t.Fatal(err)- }-- config := DefaultConfig()- config.Type = SandboxTypeLocal- config.EnvVars = map[string]string{- "WORKSPACE_VALUE": "from-workspace",- "OVERRIDE_VALUE": "workspace-default",- }- manager, err := NewManager(config)- if err != nil {- t.Fatal(err)- }-- result, err := manager.Execute(context.Background(), &ExecuteConfig{- Script: scriptPath,- ScriptContent: scriptContent,- Env: map[string]string{"OVERRIDE_VALUE": "per-execution"},- Timeout: 10 * time.Second,- })- if err != nil {- t.Fatal(err)- }- if result.Stdout != "from-workspace|per-execution" {- t.Fatalf("unexpected environment output %q", result.Stdout)- }-}--func TestLocalSandboxTimeout(t *testing.T) {- // Create a temporary script that sleeps- tmpDir, err := os.MkdirTemp("", "sandbox-test")- if err != nil {- t.Fatalf("Failed to create temp dir: %v", err)- }- defer os.RemoveAll(tmpDir)-- // Write a script that sleeps- scriptPath := filepath.Join(tmpDir, "sleep.sh")- scriptContent := `#!/bin/bash-sleep 10-echo "Done"-`- if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {- t.Fatalf("Failed to write script: %v", err)- }-- // Create local sandbox- config := DefaultConfig()- config.Type = SandboxTypeLocal- sandbox := NewLocalSandbox(config)-- // Execute with short timeout- ctx := context.Background()- result, err := sandbox.Execute(ctx, &ExecuteConfig{- Script: scriptPath,- Timeout: 1 * time.Second,- })-- if err != nil {- t.Fatalf("Execute should not return error, got: %v", err)- }-- if !result.Killed {- t.Error("Expected script to be killed due to timeout")- }-- t.Logf("Script was killed: %v, Duration: %v", result.Killed, result.Duration)-}-func TestNewManager(t *testing.T) {config := DefaultConfig()- config.Type = SandboxTypeLocal+ config.Type = SandboxTypeDisabledmanager, err := NewManager(config)if err != nil {t.Fatalf("Failed to create manager: %v", err)}- if manager.GetType() != SandboxTypeLocal {- t.Errorf("Expected type local, got %s", manager.GetType())+ if manager.GetType() != SandboxTypeDisabled {+ t.Errorf("Expected type disabled, got %s", manager.GetType())}}@@ -217,7 +92,6 @@ func TestNewDisabledManager(t *testing.T) {t.Errorf("Expected type disabled, got %s", manager.GetType())}- // Execute should failctx := context.Background()_, err := manager.Execute(ctx, &ExecuteConfig{Script: "/some/script.sh",@@ -236,7 +110,7 @@ func TestIsNamedSandboxBackendType(t *testing.T) {{"cube", true},{"e2b", true},{"docker", true},- {"local", true},+ {"local", false},{"disabled", false},{"", false},} {@@ -247,7 +121,6 @@ func TestIsNamedSandboxBackendType(t *testing.T) {}func TestExecuteResultHelpers(t *testing.T) {- // Test IsSuccesssuccessResult := &ExecuteResult{ExitCode: 0,Stdout: "output",@@ -271,48 +144,4 @@ func TestExecuteResultHelpers(t *testing.T) {if killedResult.IsSuccess() {t.Error("Expected IsSuccess() to return false when killed")}--}--func TestPythonScriptExecution(t *testing.T) {- // Create a temporary Python script- tmpDir, err := os.MkdirTemp("", "sandbox-test")- if err != nil {- t.Fatalf("Failed to create temp dir: %v", err)- }- defer os.RemoveAll(tmpDir)-- // Write a Python script- scriptPath := filepath.Join(tmpDir, "test.py")- scriptContent := `#!/usr/bin/env python3-import sys-print("Hello from Python")-print(f"Arguments: {sys.argv[1:]}")-`- if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {- t.Fatalf("Failed to write script: %v", err)- }-- // Create local sandbox- config := DefaultConfig()- config.Type = SandboxTypeLocal- sandbox := NewLocalSandbox(config)-- // Execute Python script- ctx := context.Background()- result, err := sandbox.Execute(ctx, &ExecuteConfig{- Script: scriptPath,- Args: []string{"test", "args"},- Timeout: 10 * time.Second,- })-- if err != nil {- t.Fatalf("Failed to execute Python script: %v", err)- }-- if result.ExitCode != 0 {- t.Errorf("Expected exit code 0, got %d. Stderr: %s", result.ExitCode, result.Stderr)- }-- t.Logf("Python script output: %s", result.Stdout)}diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.goindex 3b503fae9..01f7e6dba 100644--- a/internal/sandbox/session_manager.go+++ b/internal/sandbox/session_manager.go@@ -18,11 +18,6 @@// - An Execute call with an empty SessionID falls through to a stateless// RemoteSandbox, which allocates a fresh sandbox, runs the script, and// tears the sandbox down after Execute returns.-// - When the remote provider's Health probe fails at construction time and-// config.FallbackEnabled is true, the manager falls back to LocalSandbox.-// Every session-scoped capability (shell exec, file staging, session-// filesystem inspection) then refuses to run on the host: those calls-// require a real remote provider.// - Cube and E2B reap idle sandboxes themselves. Docker has no provider TTL,// so that backend runs its own idle sweep against activity-marker mtimes.package sandbox@@ -69,9 +64,9 @@ const sessionLifecycleCleanupTimeout = 30 * time.Second// SessionBoundManager is a sandbox.Manager that binds one remote sandbox per// tenant session. Concrete provider work is delegated to RemoteSandboxClient;-// this type owns validation, fallback, and the mapping between application-// concepts (ExecuteConfig, session-scoped shell/file APIs) and the provider--// neutral RemoteSandboxClient contract.+// this type owns validation and the mapping between application concepts+// (ExecuteConfig, session-scoped shell/file APIs) and the provider-neutral+// RemoteSandboxClient contract.type SessionBoundManager struct {config *Configvalidator *ScriptValidator@@ -82,13 +77,7 @@ type SessionBoundManager struct {lifecycle *remoteSessionLifecycleephemeral *RemoteSandbox- // fallback is used when the remote provider's health probe fails at- // construction time. Nil when the remote provider is healthy.- fallback Sandbox-- // activeType is the effective sandbox type callers observe. It equals- // client.Provider() in the normal path and the fallback sandbox's Type()- // after Local fallback engages.+ // activeType is the effective sandbox type callers observe.activeType SandboxType// mu guards Cleanup's idempotency flag.@@ -110,9 +99,9 @@ type SessionBoundManagerConfig struct {// touching another that shares the same provider account.ConfigID string- // SkipHealthProbe skips the construction-time Health() round-trip and,- // with it, the Local fallback. Set by the per-tenant resolver, which- // builds a manager per request. See NewSessionBoundManager.+ // SkipHealthProbe skips the construction-time Health() round-trip.+ // Set by the per-tenant resolver, which builds a manager per request.+ // See NewSessionBoundManager.SkipHealthProbe bool}@@ -124,10 +113,6 @@ type SessionBoundManagerConfig struct {// Provider identity comes from deps.Client.Provider() — not Config.Type —// so test harnesses and custom wiring that inject a different client backend// always project the correct template, TTL, and health timeout.-//-// When the client's Health probe fails and config.FallbackEnabled is true,-// the manager transparently falls back to LocalSandbox for ephemeral Execute-// calls. Session-scoped capabilities remain refused in that mode.func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManager, error) {cfg := deps.Configif cfg == nil {@@ -204,10 +189,9 @@ func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManage}// Per-tenant managers are rebuilt on every request, so probing here would- // add a remote round-trip to each one. Skipping also disables the Local- // fallback below, which is deliberate: when a tenant explicitly configures- // a backend, silently running their scripts in a local process is a- // surprising, security-relevant downgrade. Failing loudly is correct.+ // add a remote round-trip to each one. When a tenant explicitly configures+ // a backend, an unreachable provider must fail at first use rather than+ // substituting a different execution environment.if deps.SkipHealthProbe {return m, nil}@@ -219,19 +203,12 @@ func NewSessionBoundManager(deps SessionBoundManagerConfig) (*SessionBoundManage)defer cancel()if err := deps.Client.Health(probeCtx); err != nil {- if !cfg.FallbackEnabled {- return nil, fmt.Errorf("remote sandbox provider unavailable: %w", err)- }- log.Printf("[sandbox] remote provider %s unhealthy (%v); falling back to local sandbox",- provider, err)- m.fallback = NewLocalSandbox(cfg)- m.activeType = m.fallback.Type()+ return nil, fmt.Errorf("remote sandbox provider unavailable: %w", err)}return m, nil}-// GetType reports the current effective sandbox type. Returns the fallback-// type after Local fallback engages.+// GetType reports the current effective sandbox type.func (m *SessionBoundManager) GetType() SandboxType {if m == nil {return SandboxTypeDisabled@@ -242,17 +219,14 @@ func (m *SessionBoundManager) GetType() SandboxType {}// GetSandbox exposes a diagnostic Sandbox for callers that need to inspect-// availability. Returns the fallback when engaged, otherwise a stateless-// RemoteSandbox surface for the current provider.+// availability. Returns a stateless RemoteSandbox surface for the current+// provider.func (m *SessionBoundManager) GetSandbox() Sandbox {if m == nil {return nil}m.mu.RLock()defer m.mu.RUnlock()- if m.fallback != nil {- return m.fallback- }return m.ephemeral}@@ -269,7 +243,6 @@ func (m *SessionBoundManager) Execute(ctx context.Context, cfg *ExecuteConfig) (m.mu.RUnlock()return nil, ErrSandboxDisabled}- fallback := m.fallbackm.mu.RUnlock()if !cfg.SkipValidation {@@ -283,15 +256,6 @@ func (m *SessionBoundManager) Execute(ctx context.Context, cfg *ExecuteConfig) (}}- if fallback != nil {- if strings.TrimSpace(cfg.SessionID) != "" {- return nil, fmt.Errorf(- "sandbox: session-scoped execution requires the remote provider (current mode: %s)",- m.fallback.Type(),- )- }- return fallback.Execute(ctx, cfg)- }if strings.TrimSpace(cfg.SessionID) == "" {return m.ephemeral.Execute(ctx, cfg)}@@ -719,9 +683,8 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions(return remoteExecuteResult(execResult, execErr, duration), nil}-// SessionShellExecutor advertises the shell-execution capability while a-// real remote backend is active. Returns nil after Local fallback engages so-// the tool layer refuses to run shell commands on the host machine.+// SessionShellExecutor advertises the shell-execution capability while the+// manager is open.func (m *SessionBoundManager) SessionShellExecutor() SessionShellExecutor {if m == nil || m.remoteDisabled() {return nil@@ -730,8 +693,6 @@ func (m *SessionBoundManager) SessionShellExecutor() SessionShellExecutor {}// SessionInstallShellExecutor advertises the privileged install-mode shell.-// Same nil contract as SessionShellExecutor: after Local fallback engages the-// capability disappears, so an install can never run on the host machine.func (m *SessionBoundManager) SessionInstallShellExecutor() SessionInstallShellExecutor {if m == nil || m.remoteDisabled() {return nil@@ -756,7 +717,7 @@ func (m *SessionBoundManager) SessionFileStore() SessionFileStore {// here: their lifecycle is authoritative in the binding store and would// leak to any other WeKnora replica if this replica reaped them on shutdown.// Providers reclaim idle sandboxes via their own timeout/pause policies.-func (m *SessionBoundManager) Cleanup(ctx context.Context) error {+func (m *SessionBoundManager) Cleanup(_ context.Context) error {if m == nil {return nil}@@ -766,12 +727,7 @@ func (m *SessionBoundManager) Cleanup(ctx context.Context) error {return nil}m.closed = true- fallback := m.fallbackm.mu.Unlock()-- if fallback != nil {- return fallback.Cleanup(ctx)- }return nil}@@ -931,9 +887,12 @@ func (m *SessionBoundManager) sessionKey(}func (m *SessionBoundManager) remoteDisabled() bool {+ if m == nil {+ return true+ }m.mu.RLock()defer m.mu.RUnlock()- return m.fallback != nil || m.closed+ return m.closed}func (m *SessionBoundManager) requireRemoteBackend() error {@@ -945,12 +904,6 @@ func (m *SessionBoundManager) requireRemoteBackend() error {if m.closed {return ErrSandboxDisabled}- if m.fallback != nil {- return fmt.Errorf(- "sandbox: remote-only capability requires the remote provider (current mode: %s)",- m.fallback.Type(),- )- }return nil}diff --git a/internal/sandbox/skill_image.go b/internal/sandbox/skill_image.goindex 5f1c1e92d..c1ba8d16a 100644--- a/internal/sandbox/skill_image.go+++ b/internal/sandbox/skill_image.go@@ -28,7 +28,7 @@ func SkillImageFingerprint(provider, apiKey, apiURL string) string {// already answers, from the same inputs: a skill announced to the model while// sessions keep booting the base template is a skill that cannot be invoked,// and one hidden while the image carries it is an install nobody can use. It is-// false for backends that cannot snapshot at all (local/disabled), which is+// false for backends that cannot snapshot at all (disabled), which is// what "the base template is kept" means for them.func SkillImageActive(tenantCfg *types.TenantSandboxConfig) bool {if tenantCfg == nil {diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.goindex a9e99b96d..53dfe29e4 100644--- a/internal/sandbox/tenant_config.go+++ b/internal/sandbox/tenant_config.go@@ -230,8 +230,6 @@ func ParseSandboxType(raw string) (SandboxType, error) {return SandboxTypeE2B, nilcase SandboxTypeDocker:return SandboxTypeDocker, nil- case SandboxTypeLocal:- return SandboxTypeLocal, nilcase SandboxTypeDisabled:return SandboxTypeDisabled, nildefault:diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.goindex 161334c82..b5596fcde 100644--- a/internal/sandbox/tenant_config_test.go+++ b/internal/sandbox/tenant_config_test.go@@ -303,7 +303,7 @@ func TestEffectiveTemplateIDPerProvider(t *testing.T) {require.Equal(t, "cube-tpl", EffectiveTemplateID(&Config{Type: SandboxTypeCube, E2BTemplate: "e2b-tpl", CubeTemplate: "cube-tpl",}))- require.Empty(t, EffectiveTemplateID(&Config{Type: SandboxTypeLocal}))+ require.Empty(t, EffectiveTemplateID(&Config{Type: SandboxTypeDisabled}))require.Empty(t, EffectiveTemplateID(nil))}@@ -500,7 +500,7 @@ func TestResolveEffectiveConfigUsesSkillSnapshotAsDockerImage(t *testing.T) {func TestSkillOwnerFingerprintForDocker(t *testing.T) {require.Empty(t, SkillOwnerFingerprint(&types.TenantSandboxConfig{SandboxType: "docker"}),"a docker type with no daemon block cannot own a snapshot")- require.Empty(t, SkillOwnerFingerprint(&types.TenantSandboxConfig{SandboxType: "local"}))+ require.Empty(t, SkillOwnerFingerprint(&types.TenantSandboxConfig{SandboxType: "disabled"}))got := SkillOwnerFingerprint(&types.TenantSandboxConfig{SandboxType: "docker",@@ -564,7 +564,7 @@ func TestSkillImageActiveAgreesWithTheResolvedTemplate(t *testing.T) {},"backend that cannot snapshot": {config: &types.TenantSandboxConfig{- SandboxType: "local",+ SandboxType: "disabled",SkillImage: &types.SkillImageConfig{SnapshotID: "snap-1", OwnerFingerprint: fp,},diff --git a/internal/sandbox/tenant_resolver.go b/internal/sandbox/tenant_resolver.goindex f4e4f55ed..dd3653cc1 100644--- a/internal/sandbox/tenant_resolver.go+++ b/internal/sandbox/tenant_resolver.go@@ -192,12 +192,6 @@ func (r *tenantSandboxResolver) Resolve(SkipHealthProbe: true,ConfigID: configID,})- case SandboxTypeLocal:- // The local backend runs scripts on the application host, so falling- // back to it silently is never right: a workspace that selected it did- // so knowingly, and one that selected something else must fail loudly.- effective.FallbackEnabled = false- return NewManager(effective)default:return NewDisabledManager(), nil}diff --git a/internal/sandbox/tenant_resolver_test.go b/internal/sandbox/tenant_resolver_test.goindex 811b2eae4..3813916e6 100644--- a/internal/sandbox/tenant_resolver_test.go+++ b/internal/sandbox/tenant_resolver_test.go@@ -78,9 +78,9 @@ func TestResolveRefusesMissingConfig(t *testing.T) {require.ErrorIs(t, err, ErrSandboxConfigNotFound)}-// Construction must not perform a Health round-trip (it happens per request),-// and skipping it must also skip the silent fallback to LocalSandbox: a tenant-// that chose E2B should never have scripts quietly run as a local process.+// Construction must not perform a Health round-trip (it happens per request).+// A tenant that chose E2B must fail at first use if that backend is unreachable,+// rather than substituting a different execution environment.func TestResolveBuildsRemoteManagerWithoutHealthProbe(t *testing.T) {resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{result: ResolvedTenantSandboxConfig{@@ -151,13 +151,12 @@ func TestResolveRefusesDockerConfigWithoutImage(t *testing.T) {require.ErrorIs(t, err, ErrSandboxConfigIncomplete)}-func TestResolveBuildsLocalManagerFromWorkspaceConfig(t *testing.T) {- resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{+func TestResolveRefusesStoredLocalConfig(t *testing.T) {+ resolver, _ := newTestResolver(t, &stubTenantConfigLoader{result: ResolvedTenantSandboxConfig{Config: &types.TenantSandboxConfig{SandboxType: "local",DefaultTimeoutSec: 17,- EnvVars: map[string]string{"WORKSPACE_FLAG": "enabled"},},Found: true,},@@ -165,9 +164,8 @@ func TestResolveBuildsLocalManagerFromWorkspaceConfig(t *testing.T) {mgr, err := resolver.Resolve(context.Background(), 42, "cfg-local")- require.NoError(t, err)- require.NotSame(t, fallback, mgr)- require.Equal(t, SandboxTypeLocal, mgr.GetType())+ require.Nil(t, mgr)+ require.ErrorIs(t, err, ErrUnsupportedSandboxType)}// No caching: the loader is consulted on every Resolve, which is what makes adiff --git a/internal/types/tenant.go b/internal/types/tenant.goindex 8d8e4d476..2dea4f2f8 100644--- a/internal/types/tenant.go+++ b/internal/types/tenant.go@@ -625,9 +625,7 @@ func (c *StorageEngineConfig) Scan(value interface{}) error {// It is self-contained: provider fields are not inherited from process// environment. Leaving a required provider field empty is rejected on save.type TenantSandboxConfig struct {- // SandboxType selects the sandbox backend. Named configs may use "cube",- // "e2b", "docker", or "local". "disabled" is reserved for the hidden- // workspace policy row.+ // SandboxType is cube, e2b, or docker; disabled is the hidden policy row.SandboxType string `json:"sandbox_type,omitempty"`// ── 通用配置(跨后端生效)──────────────────────────────────diff --git a/website-docs/01-getting-started/02-installation.md b/website-docs/01-getting-started/02-installation.mdindex 3f9d877de..cd67705d6 100644--- a/website-docs/01-getting-started/02-installation.md+++ b/website-docs/01-getting-started/02-installation.md@@ -223,7 +223,7 @@ Lite 模式通过编译期 `EDITION=lite` 与运行期 `.env.lite` 环境实现- **队列/流**:`STREAM_MANAGER_TYPE=memory`(`internal/stream/factory.go`),不需要 Redis,Asynq 分布式队列在 Lite 模式下为内存/no-op;- **前端**:`make build-lite` 会把 `frontend/dist` 复制为仓库根的 `web/`,二进制直接内嵌托管静态资源(`WEKNORA_WEB_DIR` 可指定目录,router 的 `serveFrontendStatic` 提供服务);- **文档解析**:仍可选连本地 docreader(`DOCREADER_ADDR=127.0.0.1:50051`);-- **沙箱**:Lite 启动时不预置后端;可在设置页按空间统一配置 Docker、Local、CubeSandbox 或 E2B。+- **沙箱**:Lite 启动时不预置后端;可在设置页按空间统一配置 Docker、CubeSandbox 或 E2B。```bashcp .env.lite.example .env.lite # 修改 SYSTEM_AES_KEY / JWT_SECRETdiff --git a/website-docs/03-features/07-agent.md b/website-docs/03-features/07-agent.mdindex 85d88acec..a015a9742 100644--- a/website-docs/03-features/07-agent.md+++ b/website-docs/03-features/07-agent.md@@ -35,7 +35,7 @@ WeKnora 提供两种模式,在对话框顶部切换:| Token 估算与压缩 | `internal/agent/token/` | `Estimator`(BPE 估算)与 `CompressContext`(滑动裁剪) || 记忆整合 | `internal/agent/memory/consolidator.go` | LLM 驱动的历史摘要(Memory Consolidation) || 技能系统 | `internal/agent/skills/` | SKILL.md 的发现、加载与脚本执行(Progressive Disclosure) |-| 执行沙箱 | `internal/sandbox/` | 技能脚本的 Docker / Local 隔离执行与安全校验 |+| 执行沙箱 | `internal/sandbox/` | 技能脚本的 Docker / Cube / E2B 隔离执行与安全校验 || 工具审批 | `internal/agent/approval/gate.go` | MCP 危险工具的人工审批(HITL)与会话内 OAuth 授权 || Agent 服务层 | `internal/application/service/agent_service.go` | 组装引擎:注册工具、解析 KB 元信息、初始化技能/沙箱/VLM || 会话问答入口 | `internal/application/service/session_agent_qa.go` | 从 `CustomAgent` 构建运行时 `AgentConfig` 并执行 |@@ -101,7 +101,7 @@ flowchart TBMCP["MCP 工具 mcp_{service}_{tool}"]endGATE["approval.Gate<br/>(HITL 审批 / OAuth)"]- SBX["sandbox.Manager<br/>(Docker / Local)"]+ SBX["sandbox.Manager<br/>(Docker / Cube / E2B)"]EB["event.EventBus"]H1 --> SQA --> AS --> ENG@@ -408,7 +408,7 @@ Agent 侧的启停在 `configureSkillsFromAgent`(`internal/application/service### 5.3 与沙箱(internal/sandbox)的关系-`execute_skill_script` → `skills.Manager.ExecuteScript` → `sandbox.Manager.Execute`。Docker、Local、CubeSandbox、E2B 均通过「设置 → 沙箱后端」的同一套空间配置与检查接口维护;远端模板从目标集群实时拉取,缺少 WeKnora 标准模板时自动创建。Docker/Local 每次独立执行,不写入会话沙箱绑定,也不提供 shell_exec、附件暂存与产物收集,仅适合本机开发调试。生产环境使用 E2B 协议后端:E2B Cloud、CubeSandbox,或任意 E2B 兼容控制面,接入方式见 `docs/sandbox-protocol.md`。+`execute_skill_script` → `skills.Manager.ExecuteScript` → `sandbox.Manager.Execute`。Docker、CubeSandbox、E2B 均通过「设置 → 沙箱后端」的同一套空间配置与检查接口维护;远端模板从目标集群实时拉取,缺少 WeKnora 标准模板时自动创建。三者都是会话级持久沙箱,提供 shell_exec、附件暂存与产物收集。本机开发用 Docker 后端连本机 daemon;生产环境使用 E2B 协议后端:E2B Cloud、CubeSandbox,或任意 E2B 兼容控制面,接入方式见 `docs/sandbox-protocol.md`。**Manager 与校验器**(`internal/sandbox/manager.go`、`validator.go`):每次执行前,除非 `SkipValidation`,`ScriptValidator` 会做四类静态校验,任一命中即拒绝执行并返回 `ErrSecurityViolation`:@@ -425,9 +425,7 @@ Agent 侧的启停在 `configureSkillsFromAgent`(`internal/application/service- 技能目录以只读挂载到 `/workspace`;可选 `--read-only` 根文件系统 + 64MB noexec tmpfs;- 按扩展名选择解释器(`.py`→`python3` 等)。-**Local 沙箱**(`local.go` / `local_unix.go`,Docker 不可用时的回退):解释器白名单(默认 `python`/`python3`/`node`/`bash` 及 `cat`/`grep` 等安全命令)、脚本必须为绝对路径且可选限制在 `AllowedPaths` 内、最小化环境变量、`Setpgid` 建进程组以便超时后 `SIGKILL` 整组杀掉。--Manager 初始化时:`docker` 模式先探测 `docker version`,可用则异步预拉镜像,不可用且允许回退则降级 local;`disabled` 模式的 `disabledSandbox` 拒绝一切执行。+Manager 初始化时:`disabled` 模式的 `disabledSandbox` 拒绝一切执行。### 5.4 技能执行时序图@@ -437,7 +435,7 @@ sequenceDiagramparticipant ENG as AgentEngineparticipant SK as skills.Managerparticipant VAL as ScriptValidator- participant SBX as "Sandbox(Docker / Local)"+ participant SBX as "Sandbox(Docker / Cube / E2B)"Note over LLM: system prompt 含全部技能<br/>Level 1 元数据(name + description)LLM->>ENG: "tool_call: read_skill(skill_name)"@@ -451,7 +449,7 @@ sequenceDiagramalt 校验失败VAL-->>LLM: "ExitCode=-1, ErrSecurityViolation"else 校验通过- SBX->>SBX: "docker run --rm --network none --cap-drop ALL ...<br/>或本地白名单解释器 + 进程组"+ SBX->>SBX: "会话级容器 / MicroVM 内执行"SBX-->>LLM: "stdout / stderr / exit_code / duration / killed"end```