RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
feat(sandbox): complete Go sandbox settings and live refresh (#19783)
Sbaaoui Idrissaff4273476ee
diff --git a/internal/admin/handler.go b/internal/admin/handler.goindex e0aaccdaea..e6075516f0 100644--- a/internal/admin/handler.go+++ b/internal/admin/handler.go@@ -714,7 +714,7 @@ func (h *Handler) GetVersion(c *gin.Context) {func (h *Handler) ListSandboxProviders(c *gin.Context) {providers, err := h.service.ListSandboxProviders()if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())+ writeSandboxError(c, err)return}@@ -725,13 +725,13 @@ func (h *Handler) ListSandboxProviders(c *gin.Context) {func (h *Handler) GetSandboxProviderSchema(c *gin.Context) {providerID := c.Param("provider_id")if providerID == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Provider ID is required")+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Provider ID is required")return}schema, err := h.service.GetSandboxProviderSchema(providerID)if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())+ writeSandboxError(c, err)return}@@ -740,9 +740,9 @@ func (h *Handler) GetSandboxProviderSchema(c *gin.Context) {// GetSandboxConfig handle get sandbox configfunc (h *Handler) GetSandboxConfig(c *gin.Context) {- config, err := h.service.GetSandboxConfig()+ config, err := h.service.GetSandboxConfig(c.Request.Context())if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())+ writeSandboxError(c, err)return}@@ -753,29 +753,26 @@ func (h *Handler) GetSandboxConfig(c *gin.Context) {type SetSandboxConfigHTTPRequest struct {ProviderType string `json:"provider_type" binding:"required"`Config map[string]interface{} `json:"config"`- SetActive bool `json:"set_active"`+ SetActive *bool `json:"set_active"`}// SetSandboxConfig handle set sandbox configfunc (h *Handler) SetSandboxConfig(c *gin.Context) {var req SetSandboxConfigHTTPRequestif err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Request body is required")+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid JSON request: provider_type must be a nonempty string, config an object, and set_active a boolean")return}if req.ProviderType == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Provider type is required")+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Provider type is required")return}- // Default to true for backward compatibility- _ = c.Request.Body.Close()- req.SetActive = true-- result, err := h.service.SetSandboxConfig(req.ProviderType, req.Config, req.SetActive)+ setActive := req.SetActive == nil || *req.SetActive+ result, err := h.service.SetSandboxConfig(c.Request.Context(), req.ProviderType, req.Config, setActive)if err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, err.Error())+ writeSandboxError(c, err)return}@@ -792,24 +789,37 @@ type TestSandboxConnectionHTTPRequest struct {func (h *Handler) TestSandboxConnection(c *gin.Context) {var req TestSandboxConnectionHTTPRequestif err := c.ShouldBindJSON(&req); err != nil {- common.ErrorWithCode(c, common.CodeBadRequest, "Request body is required")+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid JSON request: provider_type must be a nonempty string and config an object")return}if req.ProviderType == "" {- common.ErrorWithCode(c, common.CodeBadRequest, "Provider type is required")+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Provider type is required")return}- result, err := h.service.TestSandboxConnection(req.ProviderType, req.Config)+ result, err := h.service.TestSandboxConnection(c.Request.Context(), req.ProviderType, req.Config)if err != nil {- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid access token")+ writeSandboxError(c, err)+ return+ }+ if success, ok := result["success"].(bool); ok && !success {+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, result, "Sandbox connection test failed")return}common.SuccessWithData(c, result, "")}+func writeSandboxError(c *gin.Context, err error) {+ var coded *common.CodedError+ if errors.As(err, &coded) {+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, coded.Code, nil, coded.Message)+ return+ }+ common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeServerError, nil, err.Error())+}+// AuthMiddleware JWT auth middleware// Validates that the user is authenticated and is a superuser (admin)func (h *Handler) AuthMiddleware() gin.HandlerFunc {diff --git a/internal/admin/service.go b/internal/admin/service.goindex c30ea1ce17..6f915435e9 100644--- a/internal/admin/service.go+++ b/internal/admin/service.go@@ -21,8 +21,10 @@ import ("crypto/rand""encoding/base64""encoding/hex"+ "encoding/json""errors""fmt"+ "ragflow/internal/agent/sandbox""ragflow/internal/common""ragflow/internal/dao""ragflow/internal/engine"@@ -1370,7 +1372,11 @@ func (s *Service) ListAllVariables(ctx context.Context) ([]map[string]interface{// Creates or updates a system setting// If the setting exists, updates it; otherwise creates a new onefunc (s *Service) SetVariable(ctx context.Context, varName, varValue string) error {- settings, err := s.systemSettingsDAO.GetByName(ctx, dao.DB, varName)+ return s.setVariable(ctx, dao.DB, varName, varValue)+}++func (s *Service) setVariable(ctx context.Context, db *gorm.DB, varName, varValue string) error {+ settings, err := s.systemSettingsDAO.GetByName(ctx, db, varName)if err != nil {return err}@@ -1381,7 +1387,7 @@ func (s *Service) SetVariable(ctx context.Context, varName, varValue string) errreturn err}setting.Value = varValue- return s.systemSettingsDAO.UpdateByName(ctx, dao.DB, varName, setting)+ return s.systemSettingsDAO.UpdateByName(ctx, db, varName, setting)} else if len(settings) > 1 {return NewAdminException("Can't update more than 1 setting: " + varName)}@@ -1396,7 +1402,7 @@ func (s *Service) SetVariable(ctx context.Context, varName, varValue string) errif err = common.ValidateSystemSettingValue(*newSetting, varValue); err != nil {return err}- return s.systemSettingsDAO.Create(ctx, dao.DB, newSetting)+ return s.systemSettingsDAO.Create(ctx, db, newSetting)}// Config methods@@ -1483,40 +1489,108 @@ func (s *Service) GetVersion() (string, string) {// ListSandboxProviders list sandbox providersfunc (s *Service) ListSandboxProviders() ([]map[string]interface{}, error) {- // TODO: Implement with sandbox manager- return []map[string]interface{}{}, nil+ return sandbox.ListProviders(), nil}// GetSandboxProviderSchema get sandbox provider schemafunc (s *Service) GetSandboxProviderSchema(providerID string) (map[string]interface{}, error) {- // TODO: Implement with sandbox manager- return map[string]interface{}{}, nil+ schema, err := sandbox.ConfigSchema(providerID)+ if err != nil {+ return nil, common.NewCodedError(common.CodeBadRequest, err.Error())+ }+ return schema, nil}// GetSandboxConfig get sandbox config-func (s *Service) GetSandboxConfig() (map[string]interface{}, error) {- // TODO: Implement with sandbox manager- return map[string]interface{}{}, nil+func (s *Service) GetSandboxConfig(ctx context.Context) (map[string]interface{}, error) {+ settings, err := s.systemSettingsDAO.GetByNamePrefix(ctx, dao.DB, "sandbox.")+ if err != nil {+ return nil, err+ }++ providerType := "self_managed"+ values := make(map[string]string, len(settings))+ for _, setting := range settings {+ if _, exists := values[setting.Name]; exists {+ return nil, fmt.Errorf("duplicate sandbox setting: %s", setting.Name)+ }+ values[setting.Name] = setting.Value+ }+ if value, exists := values["sandbox.provider_type"]; exists {+ providerType = value+ }+ schema, err := sandbox.ConfigSchema(providerType)+ if err != nil {+ return nil, common.NewCodedError(common.CodeBadRequest, err.Error())+ }++ raw := values["sandbox."+providerType]+ var config map[string]interface{}+ if raw != "" {+ var value interface{}+ if err := json.Unmarshal([]byte(raw), &value); err != nil {+ config = nil+ } else if value == nil {+ return nil, common.NewCodedError(common.CodeBadRequest,+ fmt.Sprintf("sandbox.%s must contain a JSON object", providerType))+ } else if object, ok := value.(map[string]interface{}); ok {+ config = object+ } else {+ return nil, common.NewCodedError(common.CodeBadRequest,+ fmt.Sprintf("sandbox.%s must contain a JSON object", providerType))+ }+ }+ if len(config) == 0 {+ config = make(map[string]interface{})+ for name, field := range schema {+ fieldSchema, ok := field.(map[string]any)+ if !ok {+ continue+ }+ if fieldSchema["readonly"] == true {+ continue+ }+ if value, ok := fieldSchema["default"]; ok && value != nil {+ config[name] = value+ }+ }+ }+ return map[string]interface{}{"provider_type": providerType, "config": config}, nil}// SetSandboxConfig set sandbox config-func (s *Service) SetSandboxConfig(providerType string, config map[string]interface{}, setActive bool) (map[string]interface{}, error) {- // TODO: Implement with sandbox manager- return map[string]interface{}{- "provider_type": providerType,- "config": config,- "set_active": setActive,- }, nil+func (s *Service) SetSandboxConfig(ctx context.Context, providerType string, config map[string]interface{}, setActive bool) (map[string]interface{}, error) {+ if config == nil {+ return nil, common.NewCodedError(common.CodeBadRequest, "config must be a JSON object")+ }+ if err := sandbox.ValidateConfig(providerType, config); err != nil {+ return nil, common.NewCodedError(common.CodeBadRequest, err.Error())+ }+ encoded, err := json.Marshal(config)+ if err != nil {+ return nil, common.NewCodedError(common.CodeBadRequest, fmt.Sprintf("invalid sandbox configuration: %v", err))+ }+ err = s.systemSettingsDAO.Transaction(ctx, dao.DB, func(tx *gorm.DB) error {+ if setActive {+ if err := s.setVariable(ctx, tx, "sandbox.provider_type", providerType); err != nil {+ return err+ }+ }+ return s.setVariable(ctx, tx, "sandbox."+providerType, string(encoded))+ })+ if err != nil {+ return nil, err+ }+ return map[string]interface{}{"provider_type": providerType, "config": config}, nil}// TestSandboxConnection test sandbox connection-func (s *Service) TestSandboxConnection(providerType string, config map[string]interface{}) (map[string]interface{}, error) {- // TODO: Implement with sandbox manager- return map[string]interface{}{- "provider_type": providerType,- "config": config,- "connected": true,- }, nil+func (s *Service) TestSandboxConnection(ctx context.Context, providerType string, config map[string]interface{}) (map[string]interface{}, error) {+ result, err := sandbox.TestConnection(ctx, providerType, config)+ if err != nil {+ return nil, common.NewCodedError(common.CodeBadRequest, err.Error())+ }+ return result, nil}var heartBeatCount int64 = 0diff --git a/internal/admin/service_variables_test.go b/internal/admin/service_variables_test.goindex c61486985c..238ad59fc7 100644--- a/internal/admin/service_variables_test.go+++ b/internal/admin/service_variables_test.go@@ -53,9 +53,10 @@ func TestValidateSystemSettingValue(t *testing.T) {func TestInferSystemSettingDataType(t *testing.T) {tests := map[string]string{- "sandbox.self_managed": "json",- "mail.enabled": "bool",- "mail.server": "string",+ "sandbox.provider_type": "string",+ "sandbox.self_managed": "json",+ "mail.enabled": "bool",+ "mail.server": "string",}for name, want := range tests {diff --git a/internal/agent/sandbox/aliyun.go b/internal/agent/sandbox/aliyun.goindex 1fea548e5f..adb4e82959 100644--- a/internal/agent/sandbox/aliyun.go+++ b/internal/agent/sandbox/aliyun.go@@ -14,30 +14,16 @@// limitations under the License.//-// aliyun.go is the Go port of-// `agent/sandbox/providers/aliyun_codeinterpreter.py`.-//-// The Python provider uses the high-level `agentrun-sdk` Python-// package, which exposes a `Sandbox` class with `create()` /-// `connect()` / `context.execute()` / `delete_by_id()` methods.-// The Go SDK at v5.8.4 is the OpenAPI stub — it has lifecycle-// operations (CreateCodeInterpreter / DeleteCodeInterpreter /-// ListCodeInterpreters / GetCodeInterpreter) but does NOT expose-// the execute endpoint.-//-// This implementation uses the Go SDK for instance lifecycle and-// the raw agentrun REST API for the execute call. The execute-// endpoint URL and payload shape are reverse-engineered from the-// Python SDK's `agentrun.sandbox.SandboxContext.execute` behavior;-// see §17.6.1 of docs/develop/agent-go-port-design.md for the SDK gap analysis and the-// rationale for this hybrid. When the Go SDK catches up and adds-// an execute method, the raw-HTTP call below is the only thing-// that needs to be swapped.+// Aliyun uses the installed Go SDK for sandbox lifecycle and the+// Python SDK's AgentRun RAM signature for the data-plane execute endpoint.package sandboximport ("context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex""encoding/json""errors""fmt"@@ -51,25 +37,14 @@ import ("github.com/alibabacloud-go/agentrun-20250910/v5/client"agentrun "github.com/alibabacloud-go/agentrun-20250910/v5/client"openapiutil "github.com/alibabacloud-go/darabonba-openapi/v2/utils"+ "github.com/alibabacloud-go/tea/tea")// aliyunDefaultRegion is the canonical region baked into the Python// side. Operators override via AGENTRUN_REGION.const aliyunDefaultRegion = "cn-hangzhou"-// aliyunExecuteEndpoint is the raw REST endpoint the agentrun-// Python SDK hits when calling `sandbox.context.execute(code=...)`.-// Reverse-engineered from the Python SDK's HTTP transport. The-// pattern is: a code interpreter instance is created with-// CreateCodeInterpreter, and execution happens via-//-// POST https://{region}agentrun.{aliyunDomain}/2025-09-10/code-interpreter/{id}/execute-//-// The exact hostname and path prefix are subject to change in newer-// SDK versions; if the SDK is updated, refresh this constant. The-// SDK also exposes the same surface via `Sandbox.execute` in-// future Go SDK releases.-const aliyunExecutePath = "/2025-09-10/code-interpreter/%s/execute"+const aliyunExecutePath = "/sandboxes/%s/contexts/execute"// AliyunCodeInterpreterProvider is the Go port of// `agent/sandbox/providers/aliyun_codeinterpreter.py::AliyunCodeInterpreterProvider`.@@ -82,9 +57,8 @@ type AliyunCodeInterpreterProvider struct {timeout int // seconds, hard cap 30executeHost string- sdk *client.Client- helper *HTTPClient- execCtx context.Context+ sdk *client.Client+ helper *HTTPClientinitialized bool}@@ -100,33 +74,33 @@ func newAliyunProviderFromEnv() *AliyunCodeInterpreterProvider {// env vars, mirroring the admin-panel settings JSON shape.func aliyunConfigFromEnv() map[string]any {return map[string]any{- "ACCESS_KEY_ID": common.GetEnv(common.EnvAgentRunAccessKeyID),- "ACCESS_KEY_SECRET": common.GetEnv(common.EnvAgentRunAccessKeySecret),- "ACCOUNT_ID": common.GetEnv(common.EnvAgentRunAccountID),- "REGION": common.GetEnv(common.EnvAgentRunRegion),- "TEMPLATE_NAME": common.GetEnv(common.EnvAgentRunTemplateName),- "EXECUTE_HOST": common.GetEnv(common.EnvAgentRunExecuteHost),- "TIMEOUT": common.GetEnv(common.EnvAgentRunTimeout),+ "access_key_id": common.GetEnv(common.EnvAgentRunAccessKeyID),+ "access_key_secret": common.GetEnv(common.EnvAgentRunAccessKeySecret),+ "account_id": common.GetEnv(common.EnvAgentRunAccountID),+ "region": common.GetEnv(common.EnvAgentRunRegion),+ "template_name": common.GetEnv(common.EnvAgentRunTemplateName),+ "execute_host": common.GetEnv(common.EnvAgentRunExecuteHost),+ "timeout": common.GetEnv(common.EnvAgentRunTimeout),}}// newAliyunProviderFromConfig builds the provider from a JSON// config map (as stored in the system_settings table for the-// aliyun_codeinterpreter provider). The config keys mirror the-// env-var names without the AGENTRUN_ prefix.+// aliyun_codeinterpreter provider). Config keys use the lowercase+// Python schema names.func newAliyunProviderFromConfig(cfg map[string]any) *AliyunCodeInterpreterProvider {p := &AliyunCodeInterpreterProvider{- accessKeyID: configString(cfg, "ACCESS_KEY_ID"),- accessKeySecret: configString(cfg, "ACCESS_KEY_SECRET"),- accountID: configString(cfg, "ACCOUNT_ID"),- region: configString(cfg, "REGION"),- templateName: configString(cfg, "TEMPLATE_NAME"),- executeHost: configString(cfg, "EXECUTE_HOST"),+ accessKeyID: configString(cfg, "access_key_id"),+ accessKeySecret: configString(cfg, "access_key_secret"),+ accountID: configString(cfg, "account_id"),+ region: configString(cfg, "region"),+ templateName: configString(cfg, "template_name"),+ executeHost: configString(cfg, "execute_host"),}if p.region == "" {p.region = aliyunDefaultRegion}- p.timeout = configInt(cfg, "TIMEOUT", 30)+ p.timeout = configInt(cfg, "timeout", 30)// Hard cap matches the Python side.if p.timeout > 30 {p.timeout = 30@@ -139,10 +113,17 @@ func (p *AliyunCodeInterpreterProvider) ProviderType() ProviderType {return ProviderAliyun}-// Initialize constructs the agentrun SDK client and probes the-// service via ListCodeInterpreters. The Go SDK does all the auth-// and credential work for us.+// Initialize constructs the signed control-plane client without creating resources.func (p *AliyunCodeInterpreterProvider) Initialize(ctx context.Context) error {+ if p.timeout < 1 {+ return errors.New("aliyun: timeout must be at least 1 second")+ }+ endpointURL, err := normalizeAliyunEndpoint(p.executeHost)+ if err != nil {+ return err+ }+ p.executeHost = endpointURL+if p.accessKeyID == "" || p.accessKeySecret == "" {return errors.New("aliyun: AGENTRUN_ACCESS_KEY_ID and AGENTRUN_ACCESS_KEY_SECRET are required")}@@ -150,20 +131,22 @@ func (p *AliyunCodeInterpreterProvider) Initialize(ctx context.Context) error {return errors.New("aliyun: AGENTRUN_ACCOUNT_ID is required")}+ endpoint, protocol := stringPtr("agentrun."+p.region+".aliyuncs.com"), stringPtr("https")+ if p.executeHost != "" {+ u, _ := url.Parse(p.executeHost)+ endpoint = &u.Host+ }+ requestTimeout := p.timeout * 1000cfg := &openapiutil.Config{AccessKeyId: &p.accessKeyID,AccessKeySecret: &p.accessKeySecret,Type: stringPtr("access_key"),RegionId: &p.region,- Endpoint: stringPtr(p.executeHost), // empty → SDK resolves via endpoint rules- // User-Agent, SDK metadata, etc. are filled in by the SDK.- }- if p.executeHost != "" {- // explicit host override → pass through- cfg.Endpoint = &p.executeHost+ Endpoint: endpoint,+ Protocol: protocol,+ ReadTimeout: &requestTimeout,+ ConnectTimeout: &requestTimeout,}- // The SDK wants the user agent to identify us; harmless if- // omitted but useful in agentrun access logs.ua := "ragflow-go-agent"cfg.UserAgent = &ua@@ -174,18 +157,8 @@ func (p *AliyunCodeInterpreterProvider) Initialize(ctx context.Context) error {p.sdk = sdkp.helper = NewHTTPClient(HTTPConfig{Timeout: time.Duration(p.timeout) * time.Second,- MaxAttempts: 2, // aliyun already retries internally; we only retry on transport errors+ MaxAttempts: 1,})- p.execCtx = ctx-- // Probe via ListCodeInterpreters — same call Python uses for- // health_check. We accept any non-error response (empty list- // is valid for new accounts).- listReq := &client.ListCodeInterpretersRequest{}- if _, err := sdk.ListCodeInterpreters(listReq); err != nil {- return fmt.Errorf("aliyun: health probe (ListCodeInterpreters): %w", err)- }-p.initialized = truereturn nil}@@ -195,8 +168,7 @@ func (p *AliyunCodeInterpreterProvider) SupportedLanguages() []string {return []string{"python", "javascript"}}-// CreateInstance calls CreateCodeInterpreter via the SDK and returns-// the CodeInterpreterId as the instance handle.+// CreateInstance creates a sandbox from the configured or default template.func (p *AliyunCodeInterpreterProvider) CreateInstance(ctx context.Context, template string) (*SandboxInstance, error) {if !p.initialized {return nil, fmt.Errorf("aliyun: provider not initialized")@@ -208,38 +180,35 @@ func (p *AliyunCodeInterpreterProvider) CreateInstance(ctx context.Context, temptemplateName := p.templateNameif templateName == "" {- // Match the Python side: try `ragflow-{language}-default`,- // create it if it doesn't exist.templateName = fmt.Sprintf("ragflow-%s-default", lang)+ if _, err := p.sdk.GetTemplate(&templateName); err != nil {+ var sdkErr *tea.SDKError+ if !errors.As(err, &sdkErr) || sdkErr.StatusCode == nil || *sdkErr.StatusCode != http.StatusNotFound {+ return nil, fmt.Errorf("aliyun: GetTemplate: %w", err)+ }+ input := &client.CreateTemplateInput{+ TemplateName: &templateName,+ TemplateType: stringPtr("CodeInterpreter"),+ }+ if _, createErr := p.sdk.CreateTemplate(&client.CreateTemplateRequest{Body: input}); createErr != nil {+ return nil, fmt.Errorf("aliyun: CreateTemplate(%s): %w", templateName, createErr)+ }+ }}- // NOTE: Go SDK v5.8.4's CreateCodeInterpreterInput does not- // expose a TemplateName field. The Python SDK creates the- // template via the high-level `Template.create()` API and- // then references it from `Sandbox.create(template_name=...)`.- // Until the Go SDK exposes a template API or the- // CreateCodeInterpreterInput grows a TemplateName field, the- // configured templateName is recorded in metadata only — the- // create call falls back to aliyun's default template.- _ = templateName-timeout := int32(p.timeout)- input := &client.CreateCodeInterpreterInput{- CodeInterpreterName: stringPtr("ragflow-" + lang + "-" + time.Now().UTC().Format("20060102T150405Z")),- SessionIdleTimeoutSeconds: &timeout,- }- req := &client.CreateCodeInterpreterRequest{- Body: input,+ input := &client.CreateSandboxInput{+ TemplateName: &templateName,+ SandboxIdleTimeoutInSeconds: &timeout,}-- resp, err := p.sdk.CreateCodeInterpreterWithOptions(req, nil, nil)+ resp, err := p.sdk.CreateSandbox(&client.CreateSandboxRequest{Body: input})if err != nil {- return nil, fmt.Errorf("aliyun: CreateCodeInterpreter: %w", err)+ return nil, fmt.Errorf("aliyun: CreateSandbox: %w", err)}- if resp == nil || resp.Body == nil || resp.Body.Data == nil || resp.Body.Data.CodeInterpreterId == nil {- return nil, fmt.Errorf("aliyun: CreateCodeInterpreter returned empty response")+ if resp == nil || resp.Body == nil || resp.Body.Data == nil || resp.Body.Data.SandboxId == nil {+ return nil, fmt.Errorf("aliyun: CreateSandbox returned empty response")}- id := *resp.Body.Data.CodeInterpreterId+ id := *resp.Body.Data.SandboxIdreturn &SandboxInstance{InstanceID: id,@@ -250,7 +219,7 @@ func (p *AliyunCodeInterpreterProvider) CreateInstance(ctx context.Context, temp"region": p.region,"account_id": p.accountID,"template_name": templateName,- "created_at": time.Now().UTC().Format(time.RFC3339),+ "created_at": derefString(resp.Body.Data.CreatedAt),},}, nil}@@ -348,8 +317,8 @@ func (p *AliyunCodeInterpreterProvider) ExecuteCode(}}}- stdout := strings.Join(stdoutParts, "")- stderr := strings.Join(stderrParts, "")+ stdout := strings.Join(stdoutParts, "\n")+ stderr := strings.Join(stderrParts, "\n")// Strip the `__RAGFLOW_RESULT__:` marker from stdout, surface// the user's main() return value as a structured result.@@ -370,82 +339,74 @@ func (p *AliyunCodeInterpreterProvider) ExecuteCode(}, nil}-// callExecute POSTs to the execute endpoint. Auth uses the same-// access-key pair the SDK uses; the execute endpoint is the same-// REST API the SDK's `sandbox.context.execute` would hit, just-// without the SDK's higher-level helpers.-func (p *AliyunCodeInterpreterProvider) callExecute(ctx context.Context, codeInterpreterID, code, language string, timeoutSec int) ([]byte, error) {+func (p *AliyunCodeInterpreterProvider) callExecute(ctx context.Context, sandboxID, code, language string, timeoutSec int) ([]byte, error) {endpoint := p.executeHostif endpoint == "" {- // Default hostname. The aliyun agentrun service uses a- // regional endpoint; the SDK resolves this from the access- // key's account, but for raw HTTP we apply a sane default.- // Operators that need a non-default region can set- // AGENTRUN_EXECUTE_HOST explicitly.- endpoint = fmt.Sprintf("https://agentrun.%s.aliyuncs.com", p.region)+ endpoint = fmt.Sprintf("https://%s.agentrun-data.%s.aliyuncs.com", p.accountID, p.region)+ }+ endpoint, err := normalizeAliyunEndpoint(endpoint)+ if err != nil {+ return nil, err}u, err := url.Parse(endpoint)if err != nil {return nil, fmt.Errorf("aliyun: parse execute endpoint: %w", err)}- u.Path = fmt.Sprintf(aliyunExecutePath, codeInterpreterID)- endpoint = u.String()-- payload := map[string]any{- "code": code,- "language": language,- "timeout": timeoutSec,- }- body, err := json.Marshal(payload)+ u.Path = fmt.Sprintf(aliyunExecutePath, sandboxID)+ u.RawQuery = ""+ body, err := json.Marshal(map[string]any{"code": code, "language": language, "timeout": timeoutSec})if err != nil {- return nil, fmt.Errorf("aliyun: marshal execute payload: %w", err)- }-- // The agentrun REST API uses the same AccessKey auth as the- // SDK. We sign with the aliyun-pop-2017-11-11 SDK signer would- // be cleaner, but for a single endpoint with the same creds- // we can use the SDK's HTTP signer indirectly by calling- // CreateCodeInterpreter (which we did) and reading the- // signature pattern. For now, we use a minimal auth header- // that works for both v1 and v2 token patterns: the SDK's- // internal signer is invoked by the SDK's request; for raw- // HTTP we fall back to the AccessKey pair in headers. The- // exact header set is documented in- // https://help.aliyun.com/document_detail/145957.html and may- // need to be extended when this code path sees real traffic.- headers := map[string]string{- "x-ragflow-account-id": p.accountID,- "x-ragflow-region": p.region,- }-- resp, err := p.helper.Do(ctx, http.MethodPost, endpoint, string(body), "application/json", headers)+ return nil, err+ }+ resp, err := p.helper.Do(ctx, http.MethodPost, u.String(), string(body), "application/json", p.aliyunSignedHeaders(u, time.Now().UTC()))if err != nil {- return nil, fmt.Errorf("aliyun: POST execute: %w", err)+ return nil, fmt.Errorf("aliyun: execute request: %w", err)}defer resp.Body.Close()-if resp.StatusCode != http.StatusOK {- // drain for connection reuse- var b strings.Builder- _, _ = io.Copy(&b, resp.Body)- return nil, fmt.Errorf("aliyun: POST execute returned %d: %s", resp.StatusCode, b.String())- }-- var out []byte- buf := make([]byte, 1024)- for {- n, err := resp.Body.Read(buf)- if n > 0 {- out = append(out, buf[:n]...)- }- if err != nil {- break- }+ return nil, fmt.Errorf("aliyun: execute returned HTTP %d", resp.StatusCode)+ }+ return io.ReadAll(resp.Body)+}++// aliyunSignedHeaders matches agentrun-sdk's AGENTRUN4-HMAC-SHA256 signer.+// Only the fixed execute endpoint is signed; it has no query parameters.+func (p *AliyunCodeInterpreterProvider) aliyunSignedHeaders(u *url.URL, now time.Time) map[string]string {+ timestamp, date := now.UTC().Format("2006-01-02T15:04:05Z"), now.UTC().Format("20060102")+ const signed = "content-type;host;x-acs-content-sha256;x-acs-date"+ const algorithm = "AGENTRUN4-HMAC-SHA256"+ canonicalHeaders := "content-type:application/json\nhost:" + u.Host + "\nx-acs-content-sha256:UNSIGNED-PAYLOAD\nx-acs-date:" + timestamp + "\n"+ canonical := "POST\n" + u.Path + "\n\n" + canonicalHeaders + "\n" + signed + "\nUNSIGNED-PAYLOAD"+ digest := sha256.Sum256([]byte(canonical))+ key := []byte("aliyun_v4" + p.accessKeySecret)+ for _, part := range []string{date, p.region, "agentrun", "aliyun_v4_request", algorithm + "\n" + hex.EncodeToString(digest[:])} {+ mac := hmac.New(sha256.New, key)+ _, _ = mac.Write([]byte(part))+ key = mac.Sum(nil)+ }+ scope := date + "/" + p.region + "/agentrun/aliyun_v4_request"+ return map[string]string{+ "x-acs-date": timestamp,+ "x-acs-content-sha256": "UNSIGNED-PAYLOAD",+ "Agentrun-Authorization": algorithm + " Credential=" + p.accessKeyID + "/" + scope + ",SignedHeaders=" + signed + ",Signature=" + hex.EncodeToString(key),}- return out, nil}-// DestroyInstance calls DeleteCodeInterpreter via the SDK.+func normalizeAliyunEndpoint(endpoint string) (string, error) {+ if endpoint == "" {+ return "", nil+ }+ if !strings.Contains(endpoint, "://") {+ endpoint = "https://" + endpoint+ }+ u, err := url.Parse(endpoint)+ if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {+ return "", errors.New("aliyun: execute_host must be an HTTPS URL without user credentials")+ }+ return u.String(), nil+}++// DestroyInstance calls DeleteSandbox via the SDK.func (p *AliyunCodeInterpreterProvider) DestroyInstance(ctx context.Context, inst *SandboxInstance) error {if !p.initialized {return fmt.Errorf("aliyun: provider not initialized")@@ -454,24 +415,19 @@ func (p *AliyunCodeInterpreterProvider) DestroyInstance(ctx context.Context, insreturn fmt.Errorf("aliyun: instance id required")}id := inst.InstanceID- if _, err := p.sdk.DeleteCodeInterpreterWithOptions(&id, nil, nil); err != nil {- return fmt.Errorf("aliyun: DeleteCodeInterpreter(%s): %w", id, err)+ if _, err := p.sdk.DeleteSandbox(&id); err != nil {+ return fmt.Errorf("aliyun: DeleteSandbox(%s): %w", id, err)}return nil}-// HealthCheck calls ListCodeInterpreters. We use the SDK call so-// the response goes through the same auth / retry path the create-// call uses.+// HealthCheck verifies access to the template catalog.func (p *AliyunCodeInterpreterProvider) HealthCheck(ctx context.Context) error {- if p.sdk == nil {+ if !p.initialized {return errors.New("aliyun: provider not initialized")}- _, err := p.sdk.ListCodeInterpreters(&client.ListCodeInterpretersRequest{})- if err != nil {- return fmt.Errorf("aliyun: ListCodeInterpreters: %w", err)- }- return nil+ _, err := p.sdk.ListTemplates(&client.ListTemplatesRequest{})+ return err}func stringPtr(s string) *string { return &s }diff --git a/internal/agent/sandbox/aliyun_test.go b/internal/agent/sandbox/aliyun_test.gonew file mode 100644index 0000000000..172125b811--- /dev/null+++ b/internal/agent/sandbox/aliyun_test.go@@ -0,0 +1,200 @@+package sandbox++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "testing"+ "time"+)++func TestAliyun_ConfigUsesCanonicalLowercaseKeys(t *testing.T) {+ p := newAliyunProviderFromConfig(map[string]any{+ "access_key_id": "LTAI-test",+ "access_key_secret": "secret",+ "account_id": "account",+ "region": "cn-shanghai",+ "template_name": "template",+ "execute_host": "https://example.test",+ "timeout": 12,+ })+ if p.accessKeyID != "LTAI-test" || p.accessKeySecret != "secret" || p.accountID != "account" {+ t.Fatalf("lowercase credentials not applied: %#v", p)+ }+ if p.region != "cn-shanghai" || p.templateName != "template" || p.executeHost != "https://example.test" || p.timeout != 12 {+ t.Fatalf("lowercase options not applied: %#v", p)+ }+ legacy := newAliyunProviderFromConfig(map[string]any{"ACCESS_KEY_ID": "legacy", "REGION": "cn-beijing"})+ if legacy.accessKeyID != "" || legacy.region != aliyunDefaultRegion {+ t.Fatalf("uppercase configuration unexpectedly accepted: %#v", legacy)+ }+}++func TestAliyun_EnvUsesCanonicalLowercaseKeys(t *testing.T) {+ t.Setenv("AGENTRUN_ACCESS_KEY_ID", "LTAI-env")+ t.Setenv("AGENTRUN_ACCESS_KEY_SECRET", "secret")+ t.Setenv("AGENTRUN_ACCOUNT_ID", "account")+ t.Setenv("AGENTRUN_REGION", "cn-beijing")+ p := newAliyunProviderFromEnv()+ if p.accessKeyID != "LTAI-env" || p.region != "cn-beijing" {+ t.Fatalf("environment configuration not applied: %#v", p)+ }+}++func TestAliyunSignedHeadersMatchPythonSDKVector(t *testing.T) {+ p := newAliyunProviderFromConfig(map[string]any{+ "access_key_id": "LTAI-test",+ "access_key_secret": "test-secret",+ "account_id": "account",+ "region": "cn-hangzhou",+ })+ u, err := url.Parse("https://account.agentrun-data.cn-hangzhou.aliyuncs.com/sandboxes/sbx-test/contexts/execute")+ if err != nil {+ t.Fatal(err)+ }+ now := time.Date(2026, 9, 17, 0, 0, 0, 0, time.UTC)++ headers := p.aliyunSignedHeaders(u, now)+ want := "AGENTRUN4-HMAC-SHA256 Credential=LTAI-test/20260917/cn-hangzhou/agentrun/aliyun_v4_request,SignedHeaders=content-type;host;x-acs-content-sha256;x-acs-date,Signature=06d2e6526b6611609fcc76039ad0bc6f6fc3a6979f9c3fb1d5640fee6fafd150"+ if headers["Agentrun-Authorization"] != want {+ t.Fatalf("Agentrun-Authorization = %q, want %q", headers["Agentrun-Authorization"], want)+ }+ if headers["x-acs-content-sha256"] != "UNSIGNED-PAYLOAD" || headers["x-acs-date"] != "2026-09-17T00:00:00Z" {+ t.Fatalf("unexpected signed headers: %#v", headers)+ }+}++func TestAliyunProtocolUsesSavedTemplateSignedExecuteAndDelete(t *testing.T) {+ // The Aliyun SDK proxies loopback requests too, and its NO_PROXY matching+ // requires the exact host:port. Keep this local protocol test off CI proxies.+ for _, key := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy"} {+ t.Setenv(key, "")+ }+ var sawCreate, sawExecute, sawDelete bool+ var executeAuth string+ var executeBody struct {+ Code string `json:"code"`+ Language string `json:"language"`+ Timeout int `json:"timeout"`+ }++ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case r.Method == http.MethodPost && r.URL.Path == "/2025-09-10/sandboxes":+ sawCreate = true+ var body struct {+ TemplateName string `json:"templateName"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode create body: %v", err)+ }+ if body.TemplateName != "saved-template" {+ t.Errorf("templateName = %q, want saved-template", body.TemplateName)+ }+ _, _ = w.Write([]byte(`{"data":{"sandboxId":"sbx-test","status":"RUNNING","createdAt":"2026-09-17T00:00:00Z"}}`))+ case r.Method == http.MethodPost && r.URL.Path == "/sandboxes/sbx-test/contexts/execute":+ sawExecute = true+ executeAuth = r.Header.Get("Agentrun-Authorization")+ if err := json.NewDecoder(r.Body).Decode(&executeBody); err != nil {+ t.Errorf("decode execute body: %v", err)+ }+ _, _ = w.Write([]byte(`{"results":[{"type":"stdout","text":"TEST_PASSED\n"},{"type":"endOfExecution","status":"ok"}],"contextId":"ctx-test"}`))+ case r.Method == http.MethodDelete && r.URL.Path == "/2025-09-10/sandboxes/sbx-test":+ sawDelete = true+ _, _ = w.Write([]byte(`{"data":{"sandboxId":"sbx-test","status":"DELETED"}}`))+ default:+ t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)+ http.Error(w, "unexpected", http.StatusNotFound)+ }+ }))+ defer server.Close()++ p := newAliyunProviderFromConfig(map[string]any{+ "access_key_id": "LTAI-test",+ "access_key_secret": "test-secret",+ "account_id": "account",+ "region": "cn-hangzhou",+ "template_name": "saved-template",+ "execute_host": server.URL,+ "timeout": 12,+ })+ if err := p.Initialize(t.Context()); err != nil {+ t.Fatalf("initialize: %v", err)+ }+ p.sdk.HttpClient = aliyunTestHTTPClient{server.Client()}+ p.helper.client = server.Client()+ inst, err := p.CreateInstance(t.Context(), "python")+ if err != nil {+ t.Fatalf("create instance: %v", err)+ }+ result, err := p.ExecuteCode(t.Context(), inst, "def main():\n print('TEST_PASSED')", "python", 7, nil)+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ if result.ExitCode != 0 || !strings.Contains(result.Stdout, "TEST_PASSED") {+ t.Fatalf("unexpected result: %+v", result)+ }+ if executeBody.Language != "python" || executeBody.Timeout != 7 || !strings.Contains(executeBody.Code, "def main") {+ t.Fatalf("unexpected execute body: %+v", executeBody)+ }+ if !strings.HasPrefix(executeAuth, "AGENTRUN4-HMAC-SHA256 Credential=LTAI-test/") ||+ !strings.Contains(executeAuth, "SignedHeaders=content-type;host;x-acs-content-sha256;x-acs-date") {+ t.Fatalf("execute auth header = %q", executeAuth)+ }+ if err := p.DestroyInstance(t.Context(), inst); err != nil {+ t.Fatalf("destroy: %v", err)+ }+ if !sawCreate || !sawExecute || !sawDelete {+ t.Fatalf("requests seen create=%v execute=%v delete=%v", sawCreate, sawExecute, sawDelete)+ }+}++type aliyunTestHTTPClient struct{ *http.Client }++func (c aliyunTestHTTPClient) Call(req *http.Request, _ *http.Transport) (*http.Response, error) {+ return c.Do(req)+}++func TestAliyunRejectsInvalidRuntimeConfig(t *testing.T) {+ for _, timeout := range []string{"0", "-1"} {+ t.Run("timeout="+timeout, func(t *testing.T) {+ t.Setenv("AGENTRUN_TIMEOUT", timeout)+ p := newAliyunProviderFromEnv()+ p.accessKeyID, p.accessKeySecret, p.accountID = "LTAI-test", "test", "account"+ if err := p.Initialize(t.Context()); err == nil {+ t.Fatal("invalid timeout accepted")+ }+ if p.sdk != nil || p.helper != nil {+ t.Fatal("clients built before validation")+ }+ })+ }+ for _, endpoint := range []string{"http://example.test", "http://127.0.0.1:1234", "ftp://example.test", "https://", "https://user:[email protected]"} {+ t.Run(endpoint, func(t *testing.T) {+ cfg := map[string]any{"access_key_id": "LTAI-test", "access_key_secret": "test", "account_id": "account", "execute_host": endpoint}+ if err := ValidateConfig("aliyun_codeinterpreter", cfg); err == nil {+ t.Fatal("admin accepted insecure endpoint")+ }+ p := newAliyunProviderFromConfig(cfg)+ if err := p.Initialize(t.Context()); err == nil {+ t.Fatal("runtime accepted insecure endpoint")+ }+ t.Setenv("AGENTRUN_EXECUTE_HOST", endpoint)+ p = newAliyunProviderFromEnv()+ p.accessKeyID, p.accessKeySecret, p.accountID = "LTAI-test", "test", "account"+ if err := p.Initialize(t.Context()); err == nil {+ t.Fatal("environment accepted insecure endpoint")+ }+ })+ }+ p := newAliyunProviderFromConfig(map[string]any{"access_key_id": "LTAI-test", "access_key_secret": "test", "account_id": "account", "execute_host": "example.test"})+ if err := p.Initialize(t.Context()); err != nil {+ t.Fatal(err)+ }+ if p.executeHost != "https://example.test" || *p.sdk.Protocol != "https" {+ t.Fatal("endpoint not normalized to HTTPS")+ }+}diff --git a/internal/agent/sandbox/catalog.go b/internal/agent/sandbox/catalog.gonew file mode 100644index 0000000000..236a183d77--- /dev/null+++ b/internal/agent/sandbox/catalog.go@@ -0,0 +1,397 @@+package sandbox++import (+ "fmt"+ "os"+ "slices"+ "strconv"+ "strings"+)++// ValidationError marks a sandbox configuration rejected at the admin boundary.+type ValidationError struct{ Message string }++func (e *ValidationError) Error() string { return e.Message }++var providerOrder = []string{+ "local", "self_managed", "ssh", "aliyun_codeinterpreter", "e2b", "tenki", "ucloud_agent_sandbox",+}++var providerMetadata = map[string]map[string]any{+ "local": {"name": "Local", "description": "Execute code directly on the current host process.", "tags": []any{"local", "host", "minimal"}},+ "self_managed": {"name": "Self-Managed", "description": "On-premise deployment using Daytona/Docker", "tags": []any{"self-hosted", "low-latency", "secure"}},+ "ssh": {"name": "SSH", "description": "Execute code on a remote machine over SSH.", "tags": []any{"remote", "ssh", "custom-runtime"}},+ "aliyun_codeinterpreter": {"name": "Aliyun Code Interpreter", "description": "Aliyun Function Compute Code Interpreter - Code execution in serverless microVMs", "tags": []any{"saas", "cloud", "scalable", "aliyun"}},+ "e2b": {"name": "E2B", "description": "E2B Cloud - Code Execution Sandboxes", "tags": []any{"saas", "fast", "global"}},+ "tenki": {"name": "Tenki", "description": "Tenki - Disposable microVM code sandboxes", "tags": []any{"saas", "cloud", "microvm", "isolated"}},+ "ucloud_agent_sandbox": {"name": "UCloud Agent Sandbox", "description": "UCloud Agent Sandbox - Disposable cloud sandboxes for agent code execution", "tags": []any{"saas", "cloud", "isolated", "ucloud"}},+}++func field(typ string, required bool, label string) map[string]any {+ return map[string]any{"type": typ, "required": required, "label": label}+}++func ConfigSchema(provider string) (map[string]any, error) {+ if provider == "self_managed" {+ return selfManagedSchema(), nil+ }+ s := staticSchema(provider)+ if s == nil {+ return nil, &ValidationError{Message: fmt.Sprintf("unknown provider: %s", provider)}+ }+ return cloneMap(s), nil+}++func ListProviders() []map[string]any {+ result := make([]map[string]any, 0, len(providerOrder))+ for _, id := range providerOrder {+ item := cloneMap(providerMetadata[id])+ item["id"] = id+ result = append(result, item)+ }+ return result+}++func ValidateConfig(provider string, config map[string]any) error {+ if config == nil {+ return invalid("configuration must be an object")+ }+ schema, err := ConfigSchema(provider)+ if err != nil {+ return err+ }+ for name, raw := range schema {+ fieldSchema, ok := raw.(map[string]any)+ if !ok {+ continue+ }+ value, present := config[name]+ if required, _ := fieldSchema["required"].(bool); required && !present {+ return invalid("required field %q is missing", name)+ }+ if !present {+ continue+ }+ typ, _ := fieldSchema["type"].(string)+ if !validType(value, typ) {+ return invalid("field %q must be a %s", name, typ)+ }+ if typ == "integer" {+ n := integer(value)+ if min, ok := number(fieldSchema["min"]); ok && n < min {+ return invalid("field %q must be >= %v", name, fieldSchema["min"])+ }+ if max, ok := number(fieldSchema["max"]); ok && n > max {+ return invalid("field %q must be <= %v", name, fieldSchema["max"])+ }+ }+ }+ switch provider {+ case "self_managed":+ if endpoint, _ := config["endpoint"].(string); endpoint != "" && !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "https://") {+ return invalid("invalid endpoint format: %s", endpoint)+ }+ poolValue, present := config["executor_manager_pool_size"]+ if !present {+ poolValue = config["pool_size"]+ }+ if pool, ok := integerValue(poolValue); ok && pool <= 0 {+ return invalid("pool size must be greater than 0")+ }+ timeout := integerOr(config["timeout"], 30)+ if timeout < 1 || timeout > 600 {+ return invalid("timeout must be between 1 and 600 seconds")+ }+ if retries, ok := integerValue(config["max_retries"]); ok && (retries < 0 || retries > 10) {+ return invalid("max retries must be between 0 and 10")+ }+ case "ssh":+ if strings.TrimSpace(stringValue(config["host"])) == "" {+ return invalid("SSH host is required")+ }+ if strings.TrimSpace(stringValue(config["username"])) == "" {+ return invalid("SSH username is required")+ }+ if stringValue(config["password"]) == "" && stringValue(config["private_key"]) == "" {+ return invalid("Either password or private_key must be provided")+ }+ for _, key := range []string{"python_bin", "node_bin"} {+ if value, present := config[key].(string); present && value != "" && strings.TrimSpace(value) == "" {+ return invalid("%s is required", key)+ }+ }+ for _, key := range []string{"timeout", "max_output_bytes", "max_artifacts", "max_artifact_bytes"} {+ n := integerOr(config[key], 0)+ if key == "max_artifacts" {+ if n < 0 {+ return invalid("max_artifacts must be greater than or equal to 0")+ }+ } else if n <= 0 {+ return invalid("%s must be greater than 0", key)+ }+ }+ case "aliyun_codeinterpreter":+ if endpoint, present := config["execute_host"]; present {+ value, ok := endpoint.(string)+ if !ok {+ return invalid("execute_host must be a string")+ }+ if _, err := normalizeAliyunEndpoint(value); err != nil {+ return invalid("%s", err)+ }+ }+ if id := stringValue(config["access_key_id"]); id != "" && !strings.HasPrefix(id, "LTAI") {+ return invalid("invalid AccessKey ID format (should start with 'LTAI')")+ }+ if stringValue(config["account_id"]) == "" {+ return invalid("Account ID is required")+ }+ if region := stringValue(config["region"]); region != "" && !slices.Contains([]string{"cn-hangzhou", "cn-beijing", "cn-shanghai", "cn-shenzhen", "cn-guangzhou"}, region) {+ return invalid("invalid region")+ }+ case "tenki":+ if strings.TrimSpace(stringValue(config["api_key"])) == "" {+ return invalid("Tenki API key is required")+ }+ for _, key := range []string{"timeout", "max_lifetime", "max_output_bytes", "max_artifact_bytes"} {+ if integerOr(config[key], 0) <= 0 {+ return invalid("%s must be greater than 0", key)+ }+ }+ if integerOr(config["max_artifacts"], 0) < 0 {+ return invalid("max_artifacts must be greater than or equal to 0")+ }+ case "ucloud_agent_sandbox":+ if strings.TrimSpace(stringValue(config["api_key"])) == "" {+ return invalid("UCloud Agent Sandbox API key is required")+ }+ if _, present := config["template"]; present && strings.TrimSpace(stringValue(config["template"])) == "" {+ return invalid("template is required")+ }+ }+ return nil+}++func invalid(format string, args ...any) error {+ return &ValidationError{Message: fmt.Sprintf(format, args...)}+}++func validType(value any, typ string) bool {+ switch typ {+ case "string":+ _, ok := value.(string)+ return ok+ case "boolean":+ _, ok := value.(bool)+ return ok+ case "integer":+ _, ok := integerValue(value)+ return ok+ default:+ return true+ }+}++func integerValue(value any) (int64, bool) {+ switch n := value.(type) {+ case int:+ return int64(n), true+ case int8:+ return int64(n), true+ case int16:+ return int64(n), true+ case int32:+ return int64(n), true+ case int64:+ return n, true+ case float64:+ return int64(n), n == float64(int64(n))+ case float32:+ return int64(n), n == float32(int64(n))+ default:+ return 0, false+ }+}++func integer(value any) int64 { n, _ := integerValue(value); return n }+func integerOr(value any, fallback int64) int64 {+ if value == nil {+ return fallback+ }+ if n, ok := integerValue(value); ok {+ return n+ }+ return 0+}+func number(value any) (int64, bool) { return integerValue(value) }+func stringValue(value any) string {+ v, _ := value.(string)+ return v+}++func cloneMap(in map[string]any) map[string]any {+ out := make(map[string]any, len(in))+ for key, value := range in {+ switch v := value.(type) {+ case map[string]any:+ out[key] = cloneMap(v)+ case []any:+ out[key] = append([]any(nil), v...)+ default:+ out[key] = value+ }+ }+ return out+}++func env(key, fallback string) string {+ value, ok := os.LookupEnv(key)+ if ok {+ return value+ }+ return fallback+}++func envInt(key string, fallback int64) int64 {+ value, err := strconv.ParseInt(env(key, strconv.FormatInt(fallback, 10)), 10, 64)+ if err != nil {+ return fallback+ }+ return value+}++func selfManagedSchema() map[string]any {+ s := staticSchema("self_managed")+ s["executor_manager_image"].(map[string]any)["default"] = env("SANDBOX_EXECUTOR_MANAGER_IMAGE", "infiniflow/sandbox-executor-manager:latest")+ s["executor_manager_pool_size"].(map[string]any)["default"] = envInt("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", 3)+ s["base_python_image"].(map[string]any)["default"] = env("SANDBOX_BASE_PYTHON_IMAGE", "infiniflow/sandbox-base-python:latest")+ s["base_nodejs_image"].(map[string]any)["default"] = env("SANDBOX_BASE_NODEJS_IMAGE", "infiniflow/sandbox-base-nodejs:latest")+ s["executor_manager_port"].(map[string]any)["default"] = envInt("SANDBOX_EXECUTOR_MANAGER_PORT", 9385)+ s["enable_seccomp"].(map[string]any)["default"] = strings.EqualFold(env("SANDBOX_ENABLE_SECCOMP", "false"), "true")+ s["max_memory"].(map[string]any)["default"] = env("SANDBOX_MAX_MEMORY", "256m")+ s["container_network"].(map[string]any)["default"] = env("SANDBOX_CONTAINER_NETWORK", "none")+ s["sandbox_timeout"].(map[string]any)["default"] = env("SANDBOX_TIMEOUT", "10s")+ return cloneMap(s)+}++func staticSchema(provider string) map[string]any {+ switch provider {+ case "local":+ return map[string]any{+ "python_bin": fieldWith("string", false, "Python Binary", "default", "python3", "description", "Python executable used for local code execution."),+ "node_bin": fieldWith("string", false, "Node.js Binary", "default", "node", "description", "Node.js executable used for local JavaScript execution."),+ "work_dir": fieldWith("string", false, "Working Directory", "default", "/tmp/ragflow-codeexec", "description", "Directory used to store temporary scripts and artifacts on the current host."),+ "timeout": limits("integer", false, "Timeout (seconds)", 30, 1, 600, "Maximum execution time for each local run. Unit: seconds."),+ "max_memory_mb": limits("integer", false, "Max Memory (MB)", 512, 1, 65536, "Address-space memory limit for the local child process. Unit: MB."),+ "max_output_bytes": limits("integer", false, "Max Output (bytes)", 1048576, 1024, 10485760, "Maximum combined stdout and stderr size. Unit: bytes."),+ "max_artifacts": limits("integer", false, "Max Artifacts", 20, 0, 100, "Maximum number of files collected from the artifacts directory."),+ "max_artifact_bytes": limits("integer", false, "Max Artifact Size (bytes)", 10485760, 1024, 104857600, "Maximum size of a single artifact file. Unit: bytes."),+ }+ case "self_managed":+ return map[string]any{+ "endpoint": fieldWith("string", true, "Executor Manager Endpoint", "placeholder", "http://sandbox-executor-manager:9385", "default", "http://sandbox-executor-manager:9385", "description", "HTTP endpoint used by RAGFlow to call sandbox-executor-manager.", "scope", "runtime", "readonly", false),+ "api_token": fieldWith("string", false, "Executor Manager API Token", "secret", true, "placeholder", "Optional; defaults to SANDBOX_EXECUTOR_MANAGER_API_TOKEN", "default", "", "description", "Shared secret authenticating RAGFlow to sandbox-executor-manager. Must match SANDBOX_EXECUTOR_MANAGER_API_TOKEN on the executor-manager side.", "scope", "runtime", "readonly", false),+ "timeout": limitsScoped("integer", false, "Request Timeout (seconds)", 30, 5, 300, "Maximum request time for a single code execution call. Unit: seconds.", "runtime", false),+ "executor_manager_image": fieldWith("string", false, "Executor Manager Image", "default", "infiniflow/sandbox-executor-manager:latest", "description", "Docker image used by sandbox-executor-manager.", "scope", "deployment", "readonly", true),+ "executor_manager_pool_size": limitsScoped("integer", false, "Container Pool Size", int64(3), 1, 100, "Container pool size used by sandbox-executor-manager.", "deployment", true),+ "base_python_image": fieldWith("string", false, "Base Python Image", "default", "infiniflow/sandbox-base-python:latest", "description", "Python runtime image used by executor-managed containers.", "scope", "deployment", "readonly", true),+ "base_nodejs_image": fieldWith("string", false, "Base Node.js Image", "default", "infiniflow/sandbox-base-nodejs:latest", "description", "Node.js runtime image used by executor-managed containers.", "scope", "deployment", "readonly", true),+ "executor_manager_port": limitsScoped("integer", false, "Executor Manager Port", int64(9385), 1, 65535, "Host port exposed by sandbox-executor-manager.", "deployment", true),+ "enable_seccomp": fieldWith("boolean", false, "Enable Seccomp", "default", false, "description", "Whether sandbox-executor-manager starts containers with seccomp enabled.", "scope", "deployment", "readonly", true),+ "max_memory": fieldWith("string", false, "Max Memory", "default", "256m", "description", "Memory limit applied to each sandbox container. Common format: 256m or 1g.", "scope", "deployment", "readonly", true),+ "container_network": fieldWith("string", false, "Container Network", "default", "none", "description", "Docker network attached to sandbox containers. Defaults to 'none' (no external network access); set to 'bridge' only if sandboxed code needs outbound network.", "scope", "deployment", "readonly", true),+ "sandbox_timeout": fieldWith("string", false, "Sandbox Timeout", "default", "10s", "description", "Executor-manager container timeout for each sandbox run. Common format: 10s or 1m.", "scope", "deployment", "readonly", true),+ }+ case "ssh":+ return sshSchema()+ case "aliyun_codeinterpreter":+ return map[string]any{+ "access_key_id": fieldWith("string", true, "Access Key ID", "placeholder", "LTAI5t...", "description", "Aliyun AccessKey ID for authentication", "secret", false),+ "access_key_secret": fieldWith("string", true, "Access Key Secret", "placeholder", "••••••••••••••••", "description", "Aliyun AccessKey Secret for authentication", "secret", true),+ "account_id": fieldWith("string", true, "Account ID", "placeholder", "1234567890...", "description", "Aliyun primary account ID, required for API calls"),+ "region": fieldWith("string", false, "Region", "default", "cn-hangzhou", "description", "Aliyun region for Code Interpreter service", "options", []any{"cn-hangzhou", "cn-beijing", "cn-shanghai", "cn-shenzhen", "cn-guangzhou"}),+ "template_name": fieldWith("string", false, "Template Name", "placeholder", "my-interpreter", "description", "Optional sandbox template name for pre-configured environments"),+ "timeout": limits("integer", false, "Execution Timeout (seconds)", 30, 1, 30, "Code execution timeout (max 30 seconds - hard limit)"),+ }+ case "e2b":+ return map[string]any{"api_key": fieldWith("string", true, "API Key", "placeholder", "e2b_sk_...", "description", "E2B API key for authentication", "secret", true), "region": fieldWith("string", false, "Region", "default", "us", "description", "E2B service region (us or eu)"), "timeout": limits("integer", false, "Request Timeout (seconds)", 30, 5, 300, "API request timeout for code execution")}+ case "tenki":+ return tenkiSchema()+ case "ucloud_agent_sandbox":+ return ucloudSchema()+ }+ return nil+}++func fieldWith(typ string, required bool, label string, extras ...any) map[string]any {+ out := field(typ, required, label)+ for i := 0; i < len(extras); i += 2 {+ out[extras[i].(string)] = extras[i+1]+ }+ return out+}++func limits(typ string, required bool, label string, def, min, max int64, description string) map[string]any {+ return fieldWith(typ, required, label, "default", def, "min", min, "max", max, "description", description)+}++func limitsNoDescription(typ string, required bool, label string, def, min, max int64) map[string]any {+ return fieldWith(typ, required, label, "default", def, "min", min, "max", max)+}++func limitsScoped(typ string, required bool, label string, def, min, max int64, description, scope string, readonly bool) map[string]any {+ return fieldWith(typ, required, label, "default", def, "min", min, "max", max, "description", description, "scope", scope, "readonly", readonly)+}++func sshSchema() map[string]any {+ return map[string]any{+ "host": fieldWith("string", true, "SSH Host", "placeholder", "192.168.1.10", "description", "Remote host that will execute generated code."),+ "port": limits("integer", true, "SSH Port", 22, 1, 65535, "SSH port on the remote host."),+ "username": fieldWith("string", true, "SSH Username", "placeholder", "ragflow", "description", "Username used to connect to the remote host."),+ "password": fieldWith("string", false, "SSH Password", "secret", true, "placeholder", "Optional when using a private key", "description", "Password-based SSH authentication."),+ "private_key": fieldWith("string", false, "SSH Private Key", "secret", true, "multiline", true, "placeholder", "Paste PEM content or enter a local file path", "description", "Private key PEM content or a readable private key path on the RAGFlow host."),+ "passphrase": fieldWith("string", false, "Private Key Passphrase", "secret", true, "placeholder", "Optional", "description", "Passphrase for the private key if it is encrypted."),+ "known_hosts": fieldWith("string", false, "SSH known_hosts File", "placeholder", "/etc/ragflow/ssh_known_hosts", "description", "Path to an OpenSSH-format known_hosts file used to verify the remote host's key. When set, the file is loaded on top of the system host keys (~/.ssh/known_hosts). When unset, only system keys are used and unknown hosts are rejected."),+ "python_bin": fieldWith("string", false, "Python Binary", "default", "python3", "description", "Python executable used for remote code execution."),+ "node_bin": fieldWith("string", false, "Node.js Binary", "default", "node", "description", "Node.js executable used for remote JavaScript execution."),+ "work_dir": fieldWith("string", false, "Remote Workspace Root", "default", "/tmp", "placeholder", "/tmp", "description", "Writable remote directory used to create a temporary workspace."),+ "timeout": limits("integer", false, "Timeout (seconds)", 30, 1, 600, "Maximum SSH execution time for a single run."),+ "max_output_bytes": limits("integer", false, "Max Output Bytes", 1048576, 1024, 10485760, "Maximum combined stdout and stderr size."),+ "max_artifacts": limits("integer", false, "Max Artifacts", 20, 0, 100, "Maximum number of files collected from the remote artifacts directory."),+ "max_artifact_bytes": limits("integer", false, "Max Artifact Bytes", 10485760, 1024, 104857600, "Maximum size of a single artifact file in bytes."),+ }+}++func tenkiSchema() map[string]any {+ return map[string]any{+ "api_key": fieldWith("string", true, "API Key", "secret", true, "placeholder", "tk_...", "description", "Tenki API key. Create one at https://app.tenki.cloud under API Keys."),+ "base_url": fieldWith("string", false, "API Endpoint", "placeholder", "https://api.tenki.cloud", "description", "Override the Tenki API endpoint. Leave empty for the default."),+ "image": fieldWith("string", false, "Sandbox Image", "description", "Base image for sandboxes. Empty uses the Tenki default image (includes python3 and node)."),+ "allow_outbound": fieldWith("boolean", false, "Allow Outbound Network", "default", false, "description", "Security-relevant. Disabled by default so sandboxed code has no network access. Enable it to let code make outbound connections (e.g. to install packages)."),+ "timeout": limits("integer", false, "Timeout (seconds)", 30, 1, 600, "Maximum execution time for a single run."),+ "max_lifetime": limits("integer", false, "Max Sandbox Lifetime (seconds)", 3600, 60, 86400, "Tenki reclaims a sandbox after this, guarding against leaks if the run is interrupted."),+ "cpu_cores": limits("integer", false, "vCPU Cores", 0, 0, 16, "vCPU per sandbox. 0 uses the Tenki default."),+ "memory_mb": limits("integer", false, "Memory (MB)", 0, 0, 65536, "Memory per sandbox in MB. 0 uses the Tenki default."),+ "disk_size_gb": limits("integer", false, "Disk Size (GB)", 0, 0, 100, "Disk size per sandbox in GB. 0 uses the Tenki default."),+ "max_output_bytes": limits("integer", false, "Max Output Bytes", 1048576, 1024, 10485760, "Maximum combined stdout and stderr size."),+ "max_artifacts": limits("integer", false, "Max Artifacts", 20, 0, 100, "Maximum number of files collected from the sandbox artifacts directory."),+ "max_artifact_bytes": limits("integer", false, "Max Artifact Bytes", 10485760, 1024, 104857600, "Maximum size of a single artifact file in bytes."),+ }+}++func ucloudSchema() map[string]any {+ return map[string]any{+ "api_key": fieldWith("string", true, "API Key", "secret", true, "description", "UCloud Agent Sandbox API key."),+ "region": fieldWith("string", false, "Region", "default", "cn-wlcb", "description", "UCloud Agent Sandbox region, for example cn-wlcb or us-ca."),+ "domain": fieldWith("string", false, "Domain", "description", "Override the sandbox domain. Leave empty to derive it from Region."),+ "api_url": fieldWith("string", false, "API URL", "description", "Override the UCloud Agent Sandbox control-plane API URL."),+ "template": fieldWith("string", false, "Template", "default", "base", "description", "Sandbox template. The base template includes Python and Node.js."),+ "allow_internet_access": fieldWith("boolean", false, "Allow Internet Access", "default", false, "description", "Allow sandboxed code to access the internet. Disabled by default."),+ "insecure_http": fieldWith("boolean", false, "Use Insecure HTTP", "default", false, "description", "Use HTTP instead of HTTPS. Enable only for trusted private deployments."),+ "timeout": limitsNoDescription("integer", false, "Execution Timeout (seconds)", 30, 1, 600),+ "sandbox_timeout": limitsNoDescription("integer", false, "Sandbox Lifetime (seconds)", 300, 60, 86400),+ "max_output_bytes": limitsNoDescription("integer", false, "Max Output Bytes", 1048576, 1024, 10485760),+ "max_artifacts": limitsNoDescription("integer", false, "Max Artifacts", 20, 0, 100),+ "max_artifact_bytes": limitsNoDescription("integer", false, "Max Artifact Bytes", 10485760, 1024, 104857600),+ }+}diff --git a/internal/agent/sandbox/catalog_test.go b/internal/agent/sandbox/catalog_test.gonew file mode 100644index 0000000000..fb75ba4632--- /dev/null+++ b/internal/agent/sandbox/catalog_test.go@@ -0,0 +1,192 @@+package sandbox++import (+ "errors"+ "fmt"+ "maps"+ "math"+ "testing"+)++func TestCatalogOrderAndFreshSchemas(t *testing.T) {+ providers := ListProviders()+ if len(providers) != 7 {+ t.Fatalf("provider count = %d, want 7", len(providers))+ }+ for i, want := range providerOrder {+ if got := providers[i]["id"]; got != want {+ t.Errorf("provider %d = %v, want %q", i, got, want)+ }+ }+ a, err := ConfigSchema("local")+ if err != nil {+ t.Fatal(err)+ }+ a["python_bin"] = nil+ b, err := ConfigSchema("local")+ if err != nil {+ t.Fatal(err)+ }+ if b["python_bin"] == nil {+ t.Fatal("ConfigSchema returned shared mutable state")+ }+}++func TestCatalogValidationBoundaries(t *testing.T) {+ baselines := map[string]map[string]any{+ "local": {},+ "self_managed": {"endpoint": "http://localhost"},+ "ssh": {"host": "host", "username": "user", "port": 22, "password": "password", "timeout": 30, "max_output_bytes": 1024, "max_artifact_bytes": 1024},+ "aliyun_codeinterpreter": {"access_key_id": "LTAItest", "access_key_secret": "secret", "account_id": "account"},+ "e2b": {"api_key": "key"},+ "tenki": {"api_key": "key", "timeout": 30, "max_lifetime": 3600, "max_output_bytes": 1024, "max_artifact_bytes": 1024},+ "ucloud_agent_sandbox": {"api_key": "key"},+ }+ for provider, base := range baselines {+ t.Run(provider, func(t *testing.T) {+ if err := ValidateConfig(provider, base); err != nil {+ t.Fatalf("valid baseline rejected: %v", err)+ }+ if err := ValidateConfig(provider, nil); err == nil {+ t.Fatal("null object accepted")+ }+ schema, err := ConfigSchema(provider)+ if err != nil {+ t.Fatal(err)+ }+ for name, raw := range schema {+ field := raw.(map[string]any)+ if field["required"] == true {+ cfg := maps.Clone(base)+ delete(cfg, name)+ if err := ValidateConfig(provider, cfg); err == nil {+ t.Errorf("missing required field %s accepted", name)+ }+ }+ wrong := []any{nil, []any{}, map[string]any{}}+ switch field["type"] {+ case "string":+ wrong = append(wrong, 1, true)+ case "boolean":+ wrong = append(wrong, "false", 0)+ case "integer":+ wrong = append(wrong, true, "1", 1.5, math.Inf(1), math.NaN())+ }+ for _, value := range wrong {+ cfg := maps.Clone(base)+ cfg[name] = value+ if err := ValidateConfig(provider, cfg); err == nil {+ t.Errorf("%s accepted wrong type/value %T %v", name, value, value)+ }+ }+ if field["type"] == "integer" {+ lo, hi := integer(field["min"]), integer(field["max"])+ for _, value := range []int64{lo - 1, lo, hi, hi + 1} {+ cfg := maps.Clone(base)+ cfg[name] = float64(value)+ err := ValidateConfig(provider, cfg)+ if (err != nil) != (value < lo || value > hi) {+ t.Errorf("%s=%d error=%v", name, value, err)+ }+ }+ }+ }+ cfg := maps.Clone(base)+ cfg["unknown_setting"] = map[string]any{"nested": []any{1, "value"}}+ if err := ValidateConfig(provider, cfg); err != nil {+ t.Fatalf("unknown key rejected: %v", err)+ }+ })+ }+ if _, err := ConfigSchema("unknown"); err == nil {+ t.Fatal("unknown schema accepted")+ }+ if err := ValidateConfig("unknown", map[string]any{}); err == nil {+ t.Fatal("unknown provider accepted")+ }+}++func TestCatalogDynamicDeploymentDefaults(t *testing.T) {+ for env, field := range map[string]string{"SANDBOX_EXECUTOR_MANAGER_IMAGE": "executor_manager_image", "SANDBOX_BASE_PYTHON_IMAGE": "base_python_image", "SANDBOX_BASE_NODEJS_IMAGE": "base_nodejs_image", "SANDBOX_MAX_MEMORY": "max_memory", "SANDBOX_CONTAINER_NETWORK": "container_network", "SANDBOX_TIMEOUT": "sandbox_timeout"} {+ t.Setenv(env, "custom")+ schema, err := ConfigSchema("self_managed")+ if err != nil {+ t.Fatal(err)+ }+ if schema[field].(map[string]any)["default"] != "custom" {+ t.Errorf("%s default not refreshed", field)+ }+ t.Setenv(env, "")+ schema, err = ConfigSchema("self_managed")+ if err != nil {+ t.Fatal(err)+ }+ if schema[field].(map[string]any)["default"] != "" {+ t.Errorf("%s empty env lost", field)+ }+ }+ t.Setenv("SANDBOX_ENABLE_SECCOMP", "TRUE")+ t.Setenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "9")+ t.Setenv("SANDBOX_EXECUTOR_MANAGER_PORT", "9999")+ schema, err := ConfigSchema("self_managed")+ if err != nil {+ t.Fatal(err)+ }+ for field, want := range map[string]any{"enable_seccomp": true, "executor_manager_pool_size": int64(9), "executor_manager_port": int64(9999)} {+ if got := schema[field].(map[string]any)["default"]; got != want {+ t.Errorf("%s=%v want %v", field, got, want)+ }+ }+ providers := ListProviders()+ providers[0]["tags"].([]any)[0] = "changed"+ if fmt.Sprint(ListProviders()[0]["tags"]) == fmt.Sprint(providers[0]["tags"]) {+ t.Fatal("provider tags share mutable state")+ }+ schema["endpoint"].(map[string]any)["default"] = "changed"+ fresh, err := ConfigSchema("self_managed")+ if err != nil {+ t.Fatal(err)+ }+ if fresh["endpoint"].(map[string]any)["default"] == "changed" {+ t.Fatal("nested schema shares mutable state")+ }+}++func TestValidateConfigTypesRangesAndProviderRules(t *testing.T) {+ if err := ValidateConfig("local", map[string]any{"timeout": true}); err == nil {+ t.Fatal("boolean accepted as integer")+ } else {+ var validationErr *ValidationError+ if !errors.As(err, &validationErr) {+ t.Fatalf("error type = %T, want ValidationError", err)+ }+ }+ if err := ValidateConfig("local", map[string]any{"timeout": 1.5}); err == nil {+ t.Fatal("fractional integer accepted")+ }+ if err := ValidateConfig("ssh", map[string]any{"host": "h", "username": "u"}); err == nil {+ t.Fatal("SSH without authentication accepted")+ }+ if err := ValidateConfig("aliyun_codeinterpreter", map[string]any{+ "access_key_id": "bad", "access_key_secret": "secret", "account_id": "account",+ }); err == nil {+ t.Fatal("invalid Aliyun access key accepted")+ }+ if err := ValidateConfig("tenki", map[string]any{"api_key": "key", "timeout": 0}); err == nil {+ t.Fatal("invalid Tenki timeout accepted")+ }+ if err := ValidateConfig("ucloud_agent_sandbox", map[string]any{"api_key": "key", "template": ""}); err == nil {+ t.Fatal("empty UCloud template accepted")+ }+}++func TestSelfManagedPoolValidationUsesSelectedField(t *testing.T) {+ cfg := map[string]any{"endpoint": "http://localhost", "executor_manager_pool_size": 3, "pool_size": -1}+ if err := ValidateConfig("self_managed", cfg); err != nil {+ t.Fatal(err)+ }+ delete(cfg, "executor_manager_pool_size")+ if err := ValidateConfig("self_managed", cfg); err == nil {+ t.Fatal("invalid fallback pool accepted")+ }+}diff --git a/internal/agent/sandbox/config.go b/internal/agent/sandbox/config.goindex 5a8b640e2b..f30a54f8df 100644--- a/internal/agent/sandbox/config.go+++ b/internal/agent/sandbox/config.go@@ -17,18 +17,14 @@// config.go — type-safe accessors for the JSON config map that the// admin-panel settings reader passes to each provider's FromConfig.//-// The config map mirrors the env-var contract (same keys, sans the-// per-provider prefix: e.g. SANDBOX_EXECUTOR_MANAGER_URL on env ==-// "EXECUTOR_MANAGER_URL" in the config map). Values come from-// `internal/dao/system_settings.go::SystemSettingsDAO.GetByName` via-// the manager's LoadFromSettings path.+// The config map uses the canonical lowercase Python provider keys.+// Runtime values may also come from environment variables; strict+// validation of admin-supplied settings belongs at the write boundary.//-// The accessors are intentionally permissive: they accept any JSON-// shape (string, float64 from JSON numbers, bool, nested maps) and-// coerce to the target Go type. Operators that mis-configure a key-// in the admin panel get a default value (per the env-driven-// fallback) rather than a hard failure — admin-panel settings are-// best-effort overrides of the env defaults.+// The accessors are intentionally permissive for runtime environment+// values: they accept strings and JSON-decoded primitive values and+// coerce to the target Go type. Admin-supplied settings are validated+// before persistence.package sandboxdiff --git a/internal/agent/sandbox/e2b.go b/internal/agent/sandbox/e2b.goindex 83beba681f..db41dc6889 100644--- a/internal/agent/sandbox/e2b.go+++ b/internal/agent/sandbox/e2b.go@@ -44,17 +44,14 @@ import ("errors""fmt""ragflow/internal/common"+ "strings""sync""time"e2bsdk "github.com/eric642/e2b-go-sdk")-// e2bDefaultTemplate is the e2b sandbox template the operator-// expects to be on PATH. The e2b "base" template ships with-// python3 and node pre-installed; the provider does not need a-// custom template for the common case. Operators can override-// with E2B_TEMPLATE.+// e2bDefaultTemplate is the default E2B template.const e2bDefaultTemplate = "base"// e2bDefaultSandboxTimeout is the sandbox lifetime for a single@@ -73,6 +70,11 @@ type E2BProvider struct {client *e2bsdk.Clienttemplate stringsandboxTimeout time.Duration+ apiKey string+ accessToken string+ region string+ domain string+ requestTimeout time.Durationmu sync.Mutexinitialized bool@@ -87,28 +89,36 @@ func newE2BProviderFromEnv() *E2BProvider {}// e2bConfigFromEnv builds a config map from the E2B_* env vars,-// mirroring the admin-panel settings JSON shape. Note: E2B_API_KEY-// and E2B_ACCESS_TOKEN are intentionally read directly by-// Initialize (the SDK requires env or Config{}), so they are NOT-// part of the JSON config map.+// mirroring the admin-panel settings JSON shape.func e2bConfigFromEnv() map[string]any {return map[string]any{- "TEMPLATE": common.GetEnv(common.EnvE2BTemplate),- "TIMEOUT": common.GetEnv(common.EnvE2BTimeout),+ "template": common.GetEnv(common.EnvE2BTemplate),+ "timeout": common.GetEnv(common.EnvE2BTimeout),+ "api_key": common.GetEnv(common.EnvE2BAPIKey),+ "region": common.GetEnv("E2B_REGION"),+ "domain": common.GetEnv(common.EnvE2BDomain),+ "access_token": common.GetEnv(common.EnvE2BAccessToken),}}-// newE2BProviderFromConfig builds the provider from a JSON config-// map. API key / access token are read by Initialize directly-// from env (the e2b SDK requires it).+// newE2BProviderFromConfig builds the provider from a JSON config map.func newE2BProviderFromConfig(cfg map[string]any) *E2BProvider {p := &E2BProvider{- template: configString(cfg, "TEMPLATE"),+ template: configString(cfg, "template"),+ apiKey: configString(cfg, "api_key"),+ accessToken: configString(cfg, "access_token"),+ region: configString(cfg, "region"),+ domain: configString(cfg, "domain"),+ requestTimeout: time.Duration(configInt(cfg, "timeout", 30)) * time.Second,}if p.template == "" {p.template = e2bDefaultTemplate}- timeoutSec := configInt(cfg, "TIMEOUT", int(e2bDefaultSandboxTimeout.Seconds()))+ if p.region == "" {+ p.region = "us"+ }+ p.region = strings.ToLower(strings.TrimSpace(p.region))+ timeoutSec := configInt(cfg, "sandbox_timeout", int(e2bDefaultSandboxTimeout.Seconds()))if timeoutSec > 0 {p.sandboxTimeout = time.Duration(timeoutSec) * time.Second} else {@@ -120,24 +130,35 @@ func newE2BProviderFromConfig(cfg map[string]any) *E2BProvider {// ProviderType returns ProviderE2B.func (p *E2BProvider) ProviderType() ProviderType { return ProviderE2B }-// Initialize builds the e2b SDK client. The SDK reads E2B_API_KEY-// or E2B_ACCESS_TOKEN from the Config struct, which it also-// resolves from the same env vars. We return an error if neither-// is set so the manager does not register a broken provider.+// Initialize builds the E2B SDK client.func (p *E2BProvider) Initialize(ctx context.Context) error {- apiKey := common.GetEnv(common.EnvE2BAPIKey)- accessToken := common.GetEnv(common.EnvE2BAccessToken)+ if p.region != "us" && p.region != "eu" {+ return fmt.Errorf("e2b: unsupported region %q (must be us or eu)", p.region)+ }+ apiKey := p.apiKey+ if apiKey == "" {+ apiKey = common.GetEnv(common.EnvE2BAPIKey)+ }+ accessToken := p.accessToken+ if accessToken == "" {+ accessToken = common.GetEnv(common.EnvE2BAccessToken)+ }if apiKey == "" && accessToken == "" {- return errors.New(- "e2b: E2B_API_KEY or E2B_ACCESS_TOKEN env var is required " +- "(see §17.4 of docs/develop/agent-go-port-design.md for the risk register entry on the community e2b SDK)",- )+ return errors.New("e2b: api_key or E2B_API_KEY/E2B_ACCESS_TOKEN is required")+ }+ domain := p.domain+ if domain == "" {+ domain = common.GetEnv(common.EnvE2BDomain)+ }+ if strings.EqualFold(p.region, "eu") && domain == "" {+ return errors.New("e2b: domain is required for the eu region")}cfg := e2bsdk.Config{- APIKey: apiKey,- AccessToken: accessToken,- Domain: common.GetEnv(common.EnvE2BDomain),- APIURL: common.GetEnv(common.EnvE2BAPIURL),+ APIKey: apiKey,+ AccessToken: accessToken,+ Domain: domain,+ APIURL: common.GetEnv(common.EnvE2BAPIURL),+ RequestTimeout: p.requestTimeout,}c, err := e2bsdk.NewClient(cfg)if err != nil {@@ -162,20 +183,16 @@ func (p *E2BProvider) CreateInstance(ctx context.Context, template string) (*Sanif !p.isInitialized() {return nil, fmt.Errorf("e2b: provider not initialized")}- // Use the per-call template if the caller passed one; otherwise- // fall back to the configured default.- tpl := template- if tpl == "" {- tpl = p.template- }- // Validate the language to fail fast on unsupported calls.+ // The manager passes a language here; the configured template is the+ // actual E2B template identifier.lang := normalizeLanguage(template)+ if lang == "" && template == "" {+ lang = "python"+ }if lang == "" {return nil, fmt.Errorf("e2b: unsupported language %q", template)}- // CreateOptions.Template is the template id; e2b ignores the- // language hint at create time and dispatches to the right- // runtime based on the command at execute time.+ tpl := p.templateopts := e2bsdk.CreateOptions{Template: tpl,Timeout: p.sandboxTimeout,@@ -257,7 +274,7 @@ func (p *E2BProvider) ExecuteCode(TimeoutMs: timeout * 1000,})if err != nil {- return nil, fmt.Errorf("e2b: %s %v: %w", cmd, runArgs, err)+ return nil, fmt.Errorf("e2b: run %s: %w", cmd, err)}result, err := handle.Wait(ctx)if err != nil {diff --git a/internal/agent/sandbox/e2b_test.go b/internal/agent/sandbox/e2b_test.goindex 040ee61ed6..f8f9fe5557 100644--- a/internal/agent/sandbox/e2b_test.go+++ b/internal/agent/sandbox/e2b_test.go@@ -17,9 +17,9 @@package sandboximport (- "context"- "errors"- "ragflow/internal/common"+ "encoding/json"+ "net/http"+ "net/http/httptest""strings""testing""time"@@ -65,8 +65,119 @@ func TestE2BProvider_EnvOverride(t *testing.T) {if p.template != "custom-template" {t.Errorf("template = %q, want %q", p.template, "custom-template")}- if p.sandboxTimeout != 120*time.Second {- t.Errorf("sandboxTimeout = %v, want 120s", p.sandboxTimeout)+ if p.requestTimeout != 120*time.Second {+ t.Errorf("requestTimeout = %v, want 120s", p.requestTimeout)+ }+ if p.sandboxTimeout != e2bDefaultSandboxTimeout {+ t.Errorf("sandboxTimeout = %v, want %v", p.sandboxTimeout, e2bDefaultSandboxTimeout)+ }+}++func TestE2BProvider_ConfigUsesSavedSettings(t *testing.T) {+ p := newE2BProviderFromConfig(map[string]any{+ "api_key": "saved-key",+ "region": "us",+ "template": "saved-template",+ "timeout": 42,+ })+ if p.apiKey != "saved-key" || p.region != "us" || p.template != "saved-template" {+ t.Fatalf("saved settings not retained: %#v", p)+ }+ if p.requestTimeout != 42*time.Second {+ t.Fatalf("requestTimeout = %v, want 42s", p.requestTimeout)+ }+}++func TestE2BProvider_SavedConfigDrivesSDKCreateRequest(t *testing.T) {+ t.Setenv("E2B_API_KEY", "env-key")+ t.Setenv("E2B_ACCESS_TOKEN", "")+ t.Setenv("E2B_DOMAIN", "env.example.test")++ var body map[string]any+ var apiKey string+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.Method == http.MethodGet && r.URL.Path == "/sandboxes/sbx-1" {+ _, _ = w.Write([]byte(`{"sandboxID":"sbx-1","templateID":"configured-template","envdVersion":"0.4.0","clientID":"client","cpuCount":1,"memoryMB":512,"diskSizeMB":1024,"state":"running","startedAt":"2026-01-01T00:00:00Z","endAt":"2026-01-01T00:05:00Z"}`))+ return+ }+ if r.Method != http.MethodPost || r.URL.Path != "/sandboxes" {+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)+ }+ apiKey = r.Header.Get("X-API-Key")+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatal(err)+ }+ w.WriteHeader(http.StatusCreated)+ _, _ = w.Write([]byte(`{"sandboxID":"sbx-1","templateID":"configured-template","envdVersion":"0.4.0","clientID":"client"}`))+ }))+ defer server.Close()+ t.Setenv("E2B_API_URL", server.URL)++ p := newE2BProviderFromConfig(map[string]any{+ "api_key": "saved-key",+ "region": "us",+ "domain": "configured.example.test",+ "template": "configured-template",+ "timeout": 7,+ "sandbox_timeout": 123,+ })+ if err := p.Initialize(t.Context()); err != nil {+ t.Fatal(err)+ }+ inst, err := p.CreateInstance(t.Context(), "python")+ if err != nil {+ t.Fatal(err)+ }+ if inst.InstanceID != "sbx-1" {+ t.Fatalf("instance = %q", inst.InstanceID)+ }+ if apiKey != "saved-key" {+ t.Fatalf("X-API-Key = %q, want saved-key", apiKey)+ }+ if body["templateID"] != "configured-template" {+ t.Fatalf("templateID = %v, body=%v", body["templateID"], body)+ }+ if body["timeout"] != float64(123) {+ t.Fatalf("timeout = %v, body=%v", body["timeout"], body)+ }+ cfg := p.client.Config()+ if cfg.Domain != "configured.example.test" {+ t.Fatalf("domain = %q", cfg.Domain)+ }+ if cfg.RequestTimeout != 7*time.Second {+ t.Fatalf("request timeout = %v", cfg.RequestTimeout)+ }+}++func TestE2BProvider_EURequiresExplicitDomain(t *testing.T) {+ t.Setenv("E2B_API_KEY", "")+ t.Setenv("E2B_ACCESS_TOKEN", "")+ t.Setenv("E2B_DOMAIN", "")+ p := newE2BProviderFromConfig(map[string]any{"api_key": "saved-key", "region": "eu"})+ if err := p.Initialize(t.Context()); err == nil || !strings.Contains(err.Error(), "domain") {+ t.Fatalf("Initialize = %v, want missing EU domain error", err)+ }+}++func TestE2BProvider_EUUsesConfiguredDomain(t *testing.T) {+ t.Setenv("E2B_API_KEY", "")+ t.Setenv("E2B_ACCESS_TOKEN", "")+ t.Setenv("E2B_DOMAIN", "")+ p := newE2BProviderFromConfig(map[string]any{+ "api_key": "saved-key",+ "region": "eu",+ "domain": "eu.example.test",+ })+ if err := p.Initialize(t.Context()); err != nil {+ t.Fatalf("Initialize = %v", err)+ }+}++func TestE2BProvider_RejectsUnknownRegion(t *testing.T) {+ p := newE2BProviderFromConfig(map[string]any{"api_key": "saved-key", "region": "mars"})+ if err := p.Initialize(t.Context()); err == nil || !strings.Contains(err.Error(), "unsupported region") {+ t.Fatalf("Initialize = %v, want unsupported region error", err)}}@@ -88,26 +199,6 @@ func TestE2BProvider_Initialize_MissingCreds(t *testing.T) {}}-// TestE2BProvider_Initialize_WithAPIKey exercises the success-// path. This calls the e2b control plane; we skip when no API-// key is set (CI without secrets). The skip is loud via a clear-// log line so missing-secrets is visible in test output.-func TestE2BProvider_Initialize_WithAPIKey(t *testing.T) {- apiKey := common.GetEnv(common.EnvE2BAPIKey)- if apiKey == "" {- t.Skip("E2B_API_KEY not set — skipping network-dependent init check")- }- p := newE2BProviderFromEnv()- ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)- defer cancel()- if err := p.Initialize(ctx); err != nil {- t.Fatalf("Initialize: %v", err)- }- if !p.isInitialized() {- t.Errorf("provider not flagged initialized after successful build")- }-}-// TestE2BProvider_AllOps_BeforeInit verifies the "not initialized"// guard is in place for every operational method. The// initialization order is "build client" → "set initialized@@ -264,36 +355,6 @@ func makeFakeCommandResult(stdout string) *e2bsdk.CommandResult {return &e2bsdk.CommandResult{Stdout: stdout}}-// TestE2BProvider_FullE2E_SkipWithoutKey is the integration-// test path. The body is skipped unless E2B_API_KEY is set, but-// the test always runs (so missing-secrets shows up in CI logs).-// When enabled, it creates a real sandbox, runs Python, kills it.-func TestE2BProvider_FullE2E_SkipWithoutKey(t *testing.T) {- apiKey := common.GetEnv(common.EnvE2BAPIKey)- if apiKey == "" {- t.Skip("E2B_API_KEY not set — skipping full E2E test (real network call)")- }- p := newE2BProviderFromEnv()- ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)- defer cancel()- if err := p.Initialize(ctx); err != nil {- t.Fatalf("Initialize: %v", err)- }- inst, err := p.CreateInstance(ctx, "python")- if err != nil {- t.Fatalf("CreateInstance: %v", err)- }- defer func() { _ = p.DestroyInstance(ctx, inst) }()-- result, err := p.ExecuteCode(ctx, inst, "def main(): return 1+1", "python", 30, nil)- if err != nil {- t.Fatalf("ExecuteCode: %v", err)- }- if result.ExitCode != 0 {- t.Errorf("ExitCode = %d, want 0; stderr=%q", result.ExitCode, result.Stderr)- }-}-// TestE2BProvider_ProviderType_StaysDistinct ensures the// three providers do not collide on the wire. The test would// catch any future refactor that aliases them.@@ -311,26 +372,3 @@ func TestE2BProvider_ProviderType_StaysDistinct(t *testing.T) {seen[p.ProviderType()] = true}}--// TestE2BProvider_AccessTokenFallback verifies Initialize-// accepts E2B_ACCESS_TOKEN as an alternative to E2B_API_KEY.-func TestE2BProvider_AccessTokenFallback(t *testing.T) {- t.Setenv("E2B_API_KEY", "")- t.Setenv("E2B_ACCESS_TOKEN", "fake-token")- p := newE2BProviderFromEnv()- // We can't run a real e2b call here (no real token), but- // Initialize should NOT fail with "E2B_API_KEY or- // E2B_ACCESS_TOKEN is required". The error we'd see is the- // SDK's auth error, which is what we want.- ctx := t.Context()- err := p.Initialize(ctx)- if err == nil {- t.Skip("Initialize succeeded — env-var fallback accepted; skipping further checks")- }- if errors.Is(err, errors.New("")) { // placeholder- t.Errorf("unexpected error type: %v", err)- }- if strings.Contains(err.Error(), "E2B_API_KEY or E2B_ACCESS_TOKEN env var is required") {- t.Errorf("Initialize still rejected the access token: %v", err)- }-}diff --git a/internal/agent/sandbox/local.go b/internal/agent/sandbox/local.goindex 559b4149ce..7d80fd17ef 100644--- a/internal/agent/sandbox/local.go+++ b/internal/agent/sandbox/local.go@@ -117,30 +117,29 @@ func newLocalProviderFromEnv() *LocalProvider {// vars, mirroring the admin-panel settings JSON shape.func localConfigFromEnv() map[string]any {return map[string]any{- "PYTHON_BIN": common.GetEnv(common.EnvLocalPythonBin),- "NODE_BIN": common.GetEnv(common.EnvLocalNodeBin),- "WORK_DIR": common.GetEnv(common.EnvLocalWorkDir),- "TIMEOUT": common.GetEnv(common.EnvLocalTimeout),- "MAX_MEMORY_MB": common.GetEnv(common.EnvLocalMaxMemoryMB),- "MAX_OUTPUT_BYTES": common.GetEnv(common.EnvLocalMaxOutputBytes),- "MAX_ARTIFACTS": common.GetEnv(common.EnvLocalMaxArtifacts),- "MAX_ARTIFACT_BYTES": common.GetEnv(common.EnvLocalMaxArtifactBytes),+ "python_bin": common.GetEnv(common.EnvLocalPythonBin),+ "node_bin": common.GetEnv(common.EnvLocalNodeBin),+ "work_dir": common.GetEnv(common.EnvLocalWorkDir),+ "timeout": common.GetEnv(common.EnvLocalTimeout),+ "max_memory_mb": common.GetEnv(common.EnvLocalMaxMemoryMB),+ "max_output_bytes": common.GetEnv(common.EnvLocalMaxOutputBytes),+ "max_artifacts": common.GetEnv(common.EnvLocalMaxArtifacts),+ "max_artifact_bytes": common.GetEnv(common.EnvLocalMaxArtifactBytes),}}// newLocalProviderFromConfig builds the provider from a JSON-// config map. Config keys mirror the env-var names without the-// LOCAL_ prefix.+// config map. Config keys use the lowercase Python schema names.func newLocalProviderFromConfig(cfg map[string]any) *LocalProvider {p := &LocalProvider{- pythonBin: configString(cfg, "PYTHON_BIN"),- nodeBin: configString(cfg, "NODE_BIN"),- workDir: configString(cfg, "WORK_DIR"),- timeout: configInt(cfg, "TIMEOUT", localDefaultTimeout),- maxMemoryMB: configInt(cfg, "MAX_MEMORY_MB", localDefaultMaxMemoryMB),- maxOutputBytes: configInt(cfg, "MAX_OUTPUT_BYTES", localDefaultMaxOutputBytes),- maxArtifacts: configInt(cfg, "MAX_ARTIFACTS", localDefaultMaxArtifacts),- maxArtifactBytes: configInt(cfg, "MAX_ARTIFACT_BYTES", localDefaultMaxArtifactBytes),+ pythonBin: configString(cfg, "python_bin"),+ nodeBin: configString(cfg, "node_bin"),+ workDir: configString(cfg, "work_dir"),+ timeout: configInt(cfg, "timeout", localDefaultTimeout),+ maxMemoryMB: configInt(cfg, "max_memory_mb", localDefaultMaxMemoryMB),+ maxOutputBytes: configInt(cfg, "max_output_bytes", localDefaultMaxOutputBytes),+ maxArtifacts: configInt(cfg, "max_artifacts", localDefaultMaxArtifacts),+ maxArtifactBytes: configInt(cfg, "max_artifact_bytes", localDefaultMaxArtifactBytes),instances: map[string]string{},}if p.pythonBin == "" {diff --git a/internal/agent/sandbox/local_test.go b/internal/agent/sandbox/local_test.goindex bb896f3e43..04e801eb64 100644--- a/internal/agent/sandbox/local_test.go+++ b/internal/agent/sandbox/local_test.go@@ -101,6 +101,19 @@ func TestLocal_EnvOverride(t *testing.T) {}}+func TestLocal_ConfigUsesCanonicalLowercaseKeys(t *testing.T) {+ p := newLocalProviderFromConfig(map[string]any{+ "python_bin": "/custom/python", "work_dir": "/custom/work", "timeout": 12,+ })+ if p.pythonBin != "/custom/python" || p.workDir != "/custom/work" || p.timeout != 12 {+ t.Fatalf("lowercase config was not applied: %#v", p)+ }+ legacy := newLocalProviderFromConfig(map[string]any{"PYTHON_BIN": "/legacy"})+ if legacy.pythonBin == "/legacy" {+ t.Fatal("uppercase configuration unexpectedly accepted")+ }+}+func TestLocal_Initialize_CreatesWorkDir(t *testing.T) {workDir := filepath.Join(t.TempDir(), "nested", "workdir")if _, err := os.Stat(workDir); !os.IsNotExist(err) {diff --git a/internal/agent/sandbox/manager.go b/internal/agent/sandbox/manager.goindex 86adf2f6bd..493f880e84 100644--- a/internal/agent/sandbox/manager.go+++ b/internal/agent/sandbox/manager.go@@ -53,9 +53,13 @@ import (// `agent/sandbox/providers/manager.py::ProviderManager`. It is// goroutine-safe and lazily initialized.type ProviderManager struct {- mu sync.RWMutex- provider SandboxProvider- loaded bool+ refreshMu sync.Mutex+ mu sync.RWMutex+ provider SandboxProvider+ loaded bool+ override bool+ snapshot string+ settingsConfigured bool}// globalManager is the package-level manager. Mirrors the Python@@ -76,14 +80,15 @@ func DefaultManager() *ProviderManager {return globalManager}-// SetProvider installs a provider directly, bypassing env-based-// initialization. Used by tests and by the boot path once admin-panel-// settings reading is wired.+// SetProvider installs an explicit override, bypassing settings refresh.func (m *ProviderManager) SetProvider(p SandboxProvider) {+ m.refreshMu.Lock()+ defer m.refreshMu.Unlock()m.mu.Lock()defer m.mu.Unlock()m.provider = pm.loaded = true+ m.override = true}// Provider returns the active provider. nil if not yet initialized.@@ -103,10 +108,15 @@ func (m *ProviderManager) IsConfigured() bool {// Reset clears the manager. Used by reload paths and by tests.func (m *ProviderManager) Reset() {+ m.refreshMu.Lock()+ defer m.refreshMu.Unlock()m.mu.Lock()defer m.mu.Unlock()m.provider = nilm.loaded = false+ m.override = false+ m.snapshot = ""+ m.settingsConfigured = false}// InitFromEnv resolves the active provider type from@@ -118,12 +128,15 @@ func (m *ProviderManager) Reset() {// The returned error is suitable for surfacing in boot logs; the// manager stays unconfigured when Initialize fails.func (m *ProviderManager) InitFromEnv(ctx context.Context) error {- m.mu.Lock()- if m.loaded && m.provider != nil {- m.mu.Unlock()+ m.refreshMu.Lock()+ defer m.refreshMu.Unlock()+ return m.initFromEnv(ctx)+}++func (m *ProviderManager) initFromEnv(ctx context.Context) error {+ if m.IsConfigured() {return nil}- m.mu.Unlock()ptype := resolveProviderType()p, err := buildProvider(ptype)@@ -133,7 +146,9 @@ func (m *ProviderManager) InitFromEnv(ctx context.Context) error {if err := p.Initialize(ctx); err != nil {return fmt.Errorf("sandbox: initialize provider %q: %w", ptype, err)}- m.SetProvider(p)+ m.mu.Lock()+ m.provider, m.loaded = p, true+ m.mu.Unlock()return nil}@@ -147,24 +162,12 @@ type SystemSetting = entity.SystemSettings// *dao.SystemSettingsDAO directly) makes the manager unit-testable// without a real MySQL.type SettingsReader interface {- GetByName(ctx context.Context, db *gorm.DB, name string) ([]entity.SystemSettings, error)+ GetByNamePrefix(ctx context.Context, db *gorm.DB, prefix string) ([]entity.SystemSettings, error)}// LoadFromSettings resolves the active provider from the admin-panel-// `sandbox.provider_type` and `sandbox.{provider_type}` settings in-// the system_settings MySQL table. JSON-decodes the provider config-// and passes it to the provider's FromConfig constructor. Falls back-// to env-based init when:-// - the reader returns no rows (the settings haven't been written);-// - the reader returns an error (DB unreachable / table missing);-// - the provider type is unknown.-//-// This matches the Python-// `agent/sandbox/client.py::_load_provider_from_settings` flow but-// reuses the provider's FromConfig path so env-driven and-// settings-driven init produce semantically identical providers.-// Subsequent calls are no-ops once a provider is loaded; use-// Reset + ReloadFromSettings to pick up admin-panel changes.+// settings snapshot before each execution. Only absent settings permit+// environment bootstrap; explicit overrides bypass settings entirely.func (m *ProviderManager) LoadFromSettings(ctx context.Context) error {return m.LoadFromSettingsWithReader(ctx, dao.DB, dao.NewSystemSettingsDAO())}@@ -174,35 +177,42 @@ func (m *ProviderManager) LoadFromSettings(ctx context.Context) error {// uses the real *dao.SystemSettingsDAO); tests inject a fake// SettingsReader.func (m *ProviderManager) LoadFromSettingsWithReader(ctx context.Context, db *gorm.DB, r SettingsReader) error {- m.mu.Lock()- if m.loaded && m.provider != nil {- m.mu.Unlock()+ m.refreshMu.Lock()+ defer m.refreshMu.Unlock()+ if m.override {return nil}- m.mu.Unlock()ptype, cfg, err := loadSettingsConfig(ctx, db, r)+ if ptype != "" {+ m.settingsConfigured = true+ }if err != nil {- // Soft fall back: settings missing / malformed / DB error- // → use env defaults. This keeps boot resilient when the- // admin panel hasn't been configured yet.- return m.InitFromEnv(ctx)+ if errors.Is(err, errSettingsNotConfigured) && !m.settingsConfigured {+ return m.initFromEnv(ctx)+ }+ return fmt.Errorf("sandbox: read settings: %w", err)}-- p, err := buildProviderFromConfig(ptype, cfg)+ encoded, err := json.Marshal(cfg)if err != nil {- // Settings row references a provider type we don't ship- // (e.g. legacy type, typo). Fall back to env so boot- // proceeds with the operator's env config.- return m.InitFromEnv(ctx)+ return fmt.Errorf("sandbox: encode settings: %w", err)+ }+ snapshot := string(ptype) + ":" + string(encoded)+ if snapshot == m.snapshot && m.IsConfigured() {+ return nil}++ p, err := buildProviderFromConfig(ptype, cfg)if err != nil {return fmt.Errorf("sandbox: build provider %q from settings: %w", ptype, err)}if err := p.Initialize(ctx); err != nil {return fmt.Errorf("sandbox: initialize provider %q from settings: %w", ptype, err)}- m.SetProvider(p)+ m.mu.Lock()+ m.provider, m.loaded = p, true+ m.mu.Unlock()+ m.snapshot = snapshotreturn nil}@@ -226,51 +236,43 @@ func (m *ProviderManager) ReloadFromSettingsWithReader(ctx context.Context, db *// (ProviderType, nil) when the settings table has no rows for// these keys (caller falls back to env).func loadSettingsConfig(ctx context.Context, db *gorm.DB, r SettingsReader) (ProviderType, map[string]any, error) {- rows, err := r.GetByName(ctx, db, "sandbox.provider_type")+ rows, err := r.GetByNamePrefix(ctx, db, "sandbox.")if err != nil {return "", nil, err}- if len(rows) == 0 {- // No settings row at all → caller falls back to env.- return "", nil, errSettingsNotConfigured- }- ptype := ProviderType(rows[0].Value)- if ptype == "" {- return "", nil, errSettingsNotConfigured+ settings := make(map[string]string, len(rows))+ for _, row := range rows {+ if _, exists := settings[row.Name]; exists {+ return "", nil, fmt.Errorf("duplicate setting %q", row.Name)+ }+ settings[row.Name] = row.Value}-- cfgRows, err := r.GetByName(ctx, db, "sandbox."+string(ptype))- if err != nil {- return ptype, nil, err+ selected, explicit := settings["sandbox.provider_type"]+ ptype := ProviderSelfManaged+ if explicit {+ if selected == "" {+ return "", nil, errors.New("sandbox provider type is empty")+ }+ ptype = ProviderType(selected)}- if len(cfgRows) == 0 {- // Provider type set, but no per-provider config row.- // The caller will try the env-driven path for the same- // type, which may also miss if env is unconfigured for- // that type. Treat as "no settings" so the env fallback- // is uniform.- return ptype, nil, errSettingsNotConfigured+ raw, exists := settings["sandbox."+string(ptype)]+ if !exists {+ if !explicit {+ return "", nil, errSettingsNotConfigured+ }+ return ptype, nil, fmt.Errorf("missing configuration for sandbox provider %q", ptype)}var cfg map[string]any- if err := json.Unmarshal([]byte(cfgRows[0].Value), &cfg); err != nil {- // Malformed JSON: fall back to env rather than booting- // with an empty config (which would build a provider with- // zero values for every field).+ if err := json.Unmarshal([]byte(raw), &cfg); err != nil || cfg == nil {return ptype, nil, errSettingsMalformed}return ptype, cfg, nil}-// errSettingsNotConfigured signals "the admin panel hasn't-// configured sandbox settings; the env path should run." Treated-// as a soft signal: the manager swallows this and calls-// InitFromEnv, so boot never fails just because no one has-// touched the admin panel.+// errSettingsNotConfigured permits environment bootstrap before the first save.var errSettingsNotConfigured = errors.New("sandbox: admin-panel settings not configured")-// errSettingsMalformed signals "the settings JSON couldn't be-// parsed; the env path should run." Same soft-failure handling-// as errSettingsNotConfigured.+// errSettingsMalformed rejects invalid persisted configuration without fallback.var errSettingsMalformed = errors.New("sandbox: admin-panel settings JSON malformed")// resolveProviderType reads SANDBOX_PROVIDER_TYPE. Defaults to@@ -283,10 +285,7 @@ func resolveProviderType() ProviderType {return ProviderSelfManaged}-// buildProvider constructs a provider by type. Adding a new provider-// is a single switch case here. E2B returns ErrE2BProviderNotImplemented-// from every operation, but we still construct the provider so the-// manager can report the configured type to health checks.+// buildProvider constructs an environment-configured provider by type.func buildProvider(t ProviderType) (SandboxProvider, error) {switch t {case ProviderSelfManaged:@@ -309,9 +308,7 @@ func buildProvider(t ProviderType) (SandboxProvider, error) {}// buildProviderFromConfig is the settings-driven counterpart of-// buildProvider. The config map keys mirror the env-var names-// without the per-provider prefix (e.g. SANDBOX_EXECUTOR_MANAGER_URL-// on env == "EXECUTOR_MANAGER_URL" in the settings JSON).+// buildProvider. Configuration uses the canonical lowercase Python schema keys.func buildProviderFromConfig(t ProviderType, cfg map[string]any) (SandboxProvider, error) {switch t {case ProviderSelfManaged:diff --git a/internal/agent/sandbox/manager_client_test.go b/internal/agent/sandbox/manager_client_test.goindex b3c77c337a..19d7a958d0 100644--- a/internal/agent/sandbox/manager_client_test.go+++ b/internal/agent/sandbox/manager_client_test.go@@ -2,9 +2,18 @@ package sandboximport ("context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sync""testing"+ "time"+ "github.com/glebarez/sqlite"+ "gorm.io/gorm"agenttool "ragflow/internal/agent/tool"+ "ragflow/internal/dao"+ "ragflow/internal/entity")type managerClientStubProvider struct{}@@ -99,3 +108,141 @@ func (managerClientResultKeyProvider) DestroyInstance(context.Context, *SandboxI}func (managerClientResultKeyProvider) HealthCheck(context.Context) error { return nil }func (managerClientResultKeyProvider) SupportedLanguages() []string { return []string{"python"} }++func TestManagerClient_RefreshDuringExecution(t *testing.T) {+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatal(err)+ }+ sqlDB, err := db.DB()+ if err != nil {+ t.Fatal(err)+ }+ sqlDB.SetMaxOpenConns(1)+ t.Cleanup(func() { _ = sqlDB.Close() })+ if err := db.AutoMigrate(&entity.SystemSettings{}); err != nil {+ t.Fatal(err)+ }+ previousDB := dao.DB+ dao.DB = db+ t.Cleanup(func() { dao.DB = previousDB })+ started, release := make(chan struct{}), make(chan struct{})+ var once sync.Once+ oldServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/run" {+ close(started)+ select {+ case <-release:+ case <-r.Context().Done():+ return+ }+ handleRun(t, w, r, "old", "")+ }+ }))+ defer oldServer.Close()+ defer once.Do(func() { close(release) })+ newServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/run" {+ handleRun(t, w, r, "new", "")+ }+ }))+ defer newServer.Close()+ d := dao.NewSystemSettingsDAO()+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ if err := d.SaveOrCreate(ctx, db, "sandbox.provider_type", "self_managed", "admin", "string"); err != nil {+ t.Fatal(err)+ }+ save := func(endpoint string) {+ t.Helper()+ cfg, _ := json.Marshal(map[string]any{"endpoint": endpoint})+ if err := d.SaveOrCreate(ctx, db, "sandbox.self_managed", string(cfg), "admin", "json"); err != nil {+ t.Fatal(err)+ }+ }+ save(oldServer.URL)+ client := &ManagerClient{manager: &ProviderManager{}}+ type outcome struct {+ response *agenttool.SandboxResponse+ err error+ }+ done := make(chan outcome, 1)+ go func() {+ response, err := client.ExecuteCode(ctx, agenttool.SandboxRequest{Lang: "python", Script: "print('old')"})+ done <- outcome{response, err}+ }()+ select {+ case <-started:+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ save(":invalid")+ if _, err := client.ExecuteCode(ctx, agenttool.SandboxRequest{Lang: "python"}); err == nil {+ t.Fatal("new execution silently accepted failed replacement")+ }+ save(newServer.URL)+ response, err := client.ExecuteCode(ctx, agenttool.SandboxRequest{Lang: "python", Script: "print('new')"})+ if err != nil || response.Stdout != "new" {+ t.Fatalf("next execution = %+v, %v", response, err)+ }+ once.Do(func() { close(release) })+ select {+ case result := <-done:+ if result.err != nil || result.response.Stdout != "old" {+ t.Fatalf("in-flight execution = %+v, %v", result.response, result.err)+ }+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+}++type cleanupTrackingProvider struct {+ managerClientStubProvider+ started chan struct{}+ release chan struct{}+ cleaned chan struct{}+}++func (p *cleanupTrackingProvider) ExecuteCode(ctx context.Context, inst *SandboxInstance, code, lang string, timeout int, args map[string]any) (*ExecutionResult, error) {+ close(p.started)+ select {+ case <-p.release:+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ return p.managerClientStubProvider.ExecuteCode(ctx, inst, code, lang, timeout, args)+}++func (p *cleanupTrackingProvider) DestroyInstance(ctx context.Context, _ *SandboxInstance) error {+ if ctx.Err() != nil {+ return ctx.Err()+ }+ close(p.cleaned)+ return nil+}++func TestManagerClient_CleanupUsesOriginalProvider(t *testing.T) {+ p := &cleanupTrackingProvider{started: make(chan struct{}), release: make(chan struct{}), cleaned: make(chan struct{})}+ m := &ProviderManager{}+ m.SetProvider(p)+ client := &ManagerClient{manager: m}+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ done := make(chan error, 1)+ go func() { _, err := client.ExecuteCode(ctx, agenttool.SandboxRequest{Lang: "python"}); done <- err }()+ select {+ case <-p.started:+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ m.SetProvider(managerClientStubProvider{})+ close(p.release)+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ select {+ case <-p.cleaned:+ default:+ t.Fatal("original provider was not cleaned up")+ }+}diff --git a/internal/agent/sandbox/manager_test.go b/internal/agent/sandbox/manager_test.goindex 7d8fc0de30..a483b22cd5 100644--- a/internal/agent/sandbox/manager_test.go+++ b/internal/agent/sandbox/manager_test.go@@ -18,15 +18,19 @@ package sandboximport ("context"+ "encoding/json""errors""net/http""net/http/httptest""ragflow/internal/dao"+ "strings"+ "sync/atomic""testing""time""ragflow/internal/entity"+ "github.com/glebarez/sqlite""gorm.io/gorm")@@ -100,16 +104,6 @@ func TestProviderManager_BuildProvider_UnknownType(t *testing.T) {}}-func TestE2BProvider_AllOps_LoudFail(t *testing.T) {- // v3: e2b is now a real implementation. The "all ops loud-fail"- // expectation is obsolete. The new "no creds → error" path is- // covered by TestE2BProvider_Initialize_MissingCreds in- // e2b_test.go. This stub is kept as a no-op marker to make the- // migration trace explicit; remove once the test has been- // confirmed obsolete in a later cleanup pass.- t.Skip("removed in v3 — see e2b_test.go for the new behavior")-}-func TestAliyun_ProviderTypeAndLanguages(t *testing.T) {t.Parallel()p := newAliyunProviderFromEnv()@@ -268,11 +262,11 @@ func TestNewAliyunProviderFromConfig_Minimal(t *testing.T) {func TestNewAliyunProviderFromConfig_TimeoutCap(t *testing.T) {t.Parallel()p := newAliyunProviderFromConfig(map[string]any{- "ACCESS_KEY_ID": "k",- "ACCESS_KEY_SECRET": "s",- "ACCOUNT_ID": "a",- "REGION": "cn-shanghai",- "TIMEOUT": float64(120),+ "access_key_id": "k",+ "access_key_secret": "s",+ "account_id": "a",+ "region": "cn-shanghai",+ "timeout": float64(120),})if p.timeout != 30 {t.Errorf("timeout = %d, want 30 (hard cap)", p.timeout)@@ -303,13 +297,13 @@ func TestNewLocalProviderFromConfig_Defaults(t *testing.T) {func TestNewLocalProviderFromConfig_FullConfig(t *testing.T) {t.Parallel()cfg := map[string]any{- "PYTHON_BIN": "python3.12",- "NODE_BIN": "node22",- "WORK_DIR": "/var/sandbox",- "TIMEOUT": float64(60),- "MAX_OUTPUT_BYTES": float64(2_000_000),- "MAX_ARTIFACTS": float64(50),- "MAX_ARTIFACT_BYTES": float64(20_000_000),+ "python_bin": "python3.12",+ "node_bin": "node22",+ "work_dir": "/var/sandbox",+ "timeout": float64(60),+ "max_output_bytes": float64(2_000_000),+ "max_artifacts": float64(50),+ "max_artifact_bytes": float64(20_000_000),}p := newLocalProviderFromConfig(cfg)if p.pythonBin != "python3.12" {@@ -394,20 +388,193 @@ func TestBuildProviderFromConfig_SelfManaged_HappyPath(t *testing.T) {}}-// fakeSettingsReader is the test double for SettingsReader. It-// serves a hard-coded map keyed by setting name and returns-// fakeErr when non-nil (so the tests can exercise the-// "DAO returns an error → fall back to env" branch).+// fakeSettingsReader supplies a settings snapshot or a database error.type fakeSettingsReader struct {rows map[string][]entity.SystemSettingsfakeErr error}-func (f *fakeSettingsReader) GetByName(_ context.Context, _ *gorm.DB, name string) ([]entity.SystemSettings, error) {+func (f *fakeSettingsReader) GetByNamePrefix(_ context.Context, _ *gorm.DB, prefix string) ([]entity.SystemSettings, error) {if f.fakeErr != nil {return nil, f.fakeErr}- return f.rows[name], nil+ var rows []entity.SystemSettings+ for name, values := range f.rows {+ if strings.HasPrefix(name, prefix) {+ rows = append(rows, values...)+ }+ }+ return rows, nil+}++func TestProviderManager_RefreshCommittedSettings(t *testing.T) {+ var initializations atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ initializations.Add(1)+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ if err != nil {+ t.Fatal(err)+ }+ sqlDB, err := db.DB()+ if err != nil {+ t.Fatal(err)+ }+ sqlDB.SetMaxOpenConns(1)+ t.Cleanup(func() { _ = sqlDB.Close() })+ if err := db.AutoMigrate(&entity.SystemSettings{}); err != nil {+ t.Fatal(err)+ }+ d := dao.NewSystemSettingsDAO()+ ctx := t.Context()+ if err := d.SaveOrCreate(ctx, db, "sandbox.provider_type", "self_managed", "admin", "string"); err != nil {+ t.Fatal(err)+ }+ save := func(timeout int) {+ t.Helper()+ cfg, _ := json.Marshal(map[string]any{"endpoint": srv.URL, "timeout": timeout})+ if err := d.SaveOrCreate(ctx, db, "sandbox.self_managed", string(cfg), "admin", "json"); err != nil {+ t.Fatal(err)+ }+ }+ save(10)+ a, b := &ProviderManager{}, &ProviderManager{}+ for _, m := range []*ProviderManager{a, b} {+ if err := m.LoadFromSettingsWithReader(ctx, db, d); err != nil {+ t.Fatal(err)+ }+ }+ oldA, oldB := a.Provider(), b.Provider()+ if err := a.LoadFromSettingsWithReader(ctx, db, d); err != nil {+ t.Fatal(err)+ }+ if a.Provider() != oldA || initializations.Load() != 2 {+ t.Fatal("unchanged settings rebuilt provider")+ }+ if err := d.SaveOrCreate(ctx, db, "sandbox.self_managed", `{"timeout":10, "endpoint":"`+srv.URL+`"}`, "admin", "json"); err != nil {+ t.Fatal(err)+ }+ if err := a.LoadFromSettingsWithReader(ctx, db, d); err != nil {+ t.Fatal(err)+ }+ if a.Provider() != oldA {+ t.Fatal("equivalent JSON rebuilt provider")+ }+ if err := d.SaveOrCreate(ctx, db, "sandbox.ssh", `{"host":"inactive"}`, "admin", "json"); err != nil {+ t.Fatal(err)+ }+ if err := a.LoadFromSettingsWithReader(ctx, db, d); err != nil {+ t.Fatal(err)+ }+ if a.Provider() != oldA {+ t.Fatal("inactive save rebuilt active provider")+ }+ save(20)+ for _, m := range []*ProviderManager{a, b} {+ if err := m.LoadFromSettingsWithReader(ctx, db, d); err != nil {+ t.Fatal(err)+ }+ if m.Provider().(*SelfManagedProvider).timeout != 20*time.Second {+ t.Fatal("manager retained stale settings")+ }+ }+ if a.Provider() == oldA || b.Provider() == oldB {+ t.Fatal("changed settings did not replace providers")+ }+ last := a.Provider()+ dbErr := errors.New("database unavailable after configuration")+ if err := a.LoadFromSettingsWithReader(ctx, db, &fakeSettingsReader{fakeErr: dbErr}); !errors.Is(err, dbErr) {+ t.Fatalf("database error after load = %v", err)+ }+ if a.Provider() != last {+ t.Fatal("database failure discarded running provider")+ }+ if err := d.SaveOrCreate(ctx, db, "sandbox.self_managed", `{"endpoint":":invalid"}`, "admin", "json"); err != nil {+ t.Fatal(err)+ }+ if err := a.LoadFromSettingsWithReader(ctx, db, d); err == nil {+ t.Fatal("invalid replacement silently used old settings")+ }+ if a.Provider() != last {+ t.Fatal("failed replacement discarded running provider")+ }+ if err := d.DeleteByName(ctx, db, "sandbox.provider_type"); err != nil {+ t.Fatal(err)+ }+ if err := d.DeleteByName(ctx, db, "sandbox.self_managed"); err != nil {+ t.Fatal(err)+ }+ if err := a.LoadFromSettingsWithReader(ctx, db, d); err == nil {+ t.Fatal("configured manager silently fell back to environment")+ }+ localConfig, _ := json.Marshal(map[string]any{"work_dir": t.TempDir()})+ if err := d.Transaction(ctx, db, func(tx *gorm.DB) error {+ if err := d.SaveOrCreate(ctx, tx, "sandbox.local", string(localConfig), "admin", "json"); err != nil {+ return err+ }+ return d.SaveOrCreate(ctx, tx, "sandbox.provider_type", "local", "admin", "string")+ }); err != nil {+ t.Fatal(err)+ }+ for _, m := range []*ProviderManager{a, b} {+ if err := m.LoadFromSettingsWithReader(ctx, db, d); err != nil {+ t.Fatal(err)+ }+ if m.Provider().ProviderType() != ProviderLocal {+ t.Fatal("selected provider type was not refreshed")+ }+ }+}++func TestProviderManager_ConcurrentRefreshBuildsOnce(t *testing.T) {+ var initializations atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ initializations.Add(1)+ w.WriteHeader(http.StatusOK)+ }))+ defer srv.Close()+ r := &fakeSettingsReader{rows: map[string][]entity.SystemSettings{+ "sandbox.provider_type": {{Name: "sandbox.provider_type", Value: "self_managed"}},+ "sandbox.self_managed": {{Name: "sandbox.self_managed", Value: `{"endpoint":"` + srv.URL + `"}`}},+ }}+ m := &ProviderManager{}+ done := make(chan error, 12)+ for range 12 {+ go func() { done <- m.LoadFromSettingsWithReader(t.Context(), nil, r) }()+ }+ for range 12 {+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ }+ if initializations.Load() != 1 {+ t.Fatalf("initializations = %d, want 1", initializations.Load())+ }+}++func TestLoadSettingsConfig_RejectsInvalidSnapshots(t *testing.T) {+ for _, value := range []string{`null`, `[]`, `"text"`, `42`, `true`, `{broken`} {+ t.Run(value, func(t *testing.T) {+ r := &fakeSettingsReader{rows: map[string][]entity.SystemSettings{+ "sandbox.provider_type": {{Name: "sandbox.provider_type", Value: "local"}},+ "sandbox.local": {{Name: "sandbox.local", Value: value}},+ }}+ if _, _, err := loadSettingsConfig(t.Context(), nil, r); !errors.Is(err, errSettingsMalformed) {+ t.Fatalf("error = %v, want malformed settings", err)+ }+ })+ }+ for _, rows := range []map[string][]entity.SystemSettings{+ {"sandbox.provider_type": {{Name: "sandbox.provider_type", Value: "local"}}},+ {"sandbox.provider_type": {{Name: "sandbox.provider_type", Value: ""}}},+ {"sandbox.provider_type": {{Name: "sandbox.provider_type", Value: "local"}, {Name: "sandbox.provider_type", Value: "ssh"}}},+ } {+ if _, _, err := loadSettingsConfig(t.Context(), nil, &fakeSettingsReader{rows: rows}); err == nil || errors.Is(err, errSettingsNotConfigured) {+ t.Fatalf("explicit invalid snapshot error = %v", err)+ }+ }}// TestLoadFromSettingsWithReader_HappyPath pins the settings-driven@@ -502,10 +669,7 @@ func TestLoadFromSettingsWithReader_EmptyFallback(t *testing.T) {}}-// TestLoadFromSettingsWithReader_DAOErrorFallback: when the-// reader returns an error, the manager falls back to env-driven-// init (same path as the empty-rows case).-func TestLoadFromSettingsWithReader_DAOErrorFallback(t *testing.T) {+func TestLoadFromSettingsWithReader_DAOError(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path == "/healthz" {w.WriteHeader(http.StatusOK)@@ -522,18 +686,15 @@ func TestLoadFromSettingsWithReader_DAOErrorFallback(t *testing.T) {r := &fakeSettingsReader{fakeErr: errors.New("db is down")}m := &ProviderManager{}- if err := m.LoadFromSettingsWithReader(ctx, dao.DB, r); err != nil {- t.Fatalf("LoadFromSettingsWithReader (DAO error fallback): %v", err)+ if err := m.LoadFromSettingsWithReader(ctx, dao.DB, r); !errors.Is(err, r.fakeErr) {+ t.Fatalf("LoadFromSettingsWithReader error = %v, want database error", err)}- if got := m.Provider().ProviderType(); got != ProviderSelfManaged {- t.Errorf("provider type = %q, want self_managed (env fallback after DAO error)", got)+ if m.Provider() != nil {+ t.Fatal("database error silently selected an environment provider")}}-// TestLoadFromSettingsWithReader_MalformedJSONFallback: when the-// settings row exists but contains invalid JSON, the manager-// uses an empty config and falls through to env defaults.-func TestLoadFromSettingsWithReader_MalformedJSONFallback(t *testing.T) {+func TestLoadFromSettingsWithReader_MalformedJSON(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path == "/healthz" {w.WriteHeader(http.StatusOK)@@ -555,25 +716,14 @@ func TestLoadFromSettingsWithReader_MalformedJSONFallback(t *testing.T) {},}m := &ProviderManager{}- if err := m.LoadFromSettingsWithReader(ctx, dao.DB, r); err != nil {- t.Fatalf("LoadFromSettingsWithReader (malformed JSON fallback): %v", err)- }- sm, ok := m.Provider().(*SelfManagedProvider)- if !ok {- t.Fatalf("provider type = %T, want *SelfManagedProvider", m.Provider())+ if err := m.LoadFromSettingsWithReader(ctx, dao.DB, r); !errors.Is(err, errSettingsMalformed) {+ t.Fatalf("LoadFromSettingsWithReader error = %v, want malformed settings", err)}- // Empty config → default endpoint (the test server URL was- // set via env, so the manager's InitFromEnv would have used- // it; the settings path fell through to env defaults when- // JSON was malformed).- if sm.endpoint == "" {- t.Errorf("endpoint should be the env default, got empty")+ if m.Provider() != nil {+ t.Fatal("malformed settings silently selected an environment provider")}}-// TestLoadFromSettingsWithReader_UnknownProviderType covers the-// "settings row says 'foo' which we don't know" branch. The-// manager falls back to env.func TestLoadFromSettingsWithReader_UnknownProviderType(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path == "/healthz" {@@ -591,25 +741,20 @@ func TestLoadFromSettingsWithReader_UnknownProviderType(t *testing.T) {r := &fakeSettingsReader{rows: map[string][]entity.SystemSettings{- "sandbox.provider_type": {{Name: "sandbox.provider_type", Value: "mystery_provider"}},+ "sandbox.provider_type": {{Name: "sandbox.provider_type", Value: "mystery_provider"}},+ "sandbox.mystery_provider": {{Name: "sandbox.mystery_provider", Value: `{}`}},},}m := &ProviderManager{}- if err := m.LoadFromSettingsWithReader(ctx, dao.DB, r); err != nil {- t.Fatalf("LoadFromSettingsWithReader (unknown type fallback): %v", err)+ if err := m.LoadFromSettingsWithReader(ctx, dao.DB, r); err == nil {+ t.Fatal("unknown provider accepted")}- // Falls back to env-driven self_managed, NOT the unknown type.- if got := m.Provider().ProviderType(); got != ProviderSelfManaged {- t.Errorf("provider type = %q, want self_managed (env fallback)", got)+ if m.Provider() != nil {+ t.Fatal("unknown provider silently selected an environment provider")}}-// TestLoadFromSettingsWithReader_AlreadyLoaded_NoOp: once a-// provider is loaded, subsequent LoadFromSettings calls are-// no-ops. The reader is intentionally rigged to return a-// different provider type — if LoadFromSettings honored that,-// the manager would re-init; the test asserts it doesn't.-func TestLoadFromSettingsWithReader_AlreadyLoaded_NoOp(t *testing.T) {+func TestLoadFromSettingsWithReader_ExplicitOverride(t *testing.T) {m := &ProviderManager{}m.SetProvider(newSelfManagedProviderFromEnv())original := m.Provider()diff --git a/internal/agent/sandbox/probe.go b/internal/agent/sandbox/probe.gonew file mode 100644index 0000000000..b541d8b437--- /dev/null+++ b/internal/agent/sandbox/probe.go@@ -0,0 +1,104 @@+package sandbox++import (+ "context"+ "errors"+ "fmt"+ "log"+ "strings"+ "time"+)++const connectionProbeCode = `import json+import math++def main() -> dict:+ left = 2+ right = 2+ print(f"2 + 2 = {left + right}")+ print(f"JSON dump: {json.dumps({'test': 'data', 'value': 123})}")+ print(f"Math.sqrt(16) = {math.sqrt(16)}")+ print("TEST_PASSED")+ return {"ok": True, "provider_test": "TEST_PASSED"}+`++// TestConnection creates an independent provider and runs the same small+// diagnostic used by the admin endpoint. It never changes the active manager.+func TestConnection(ctx context.Context, provider string, config map[string]any) (map[string]any, error) {+ if err := ValidateConfig(provider, config); err != nil {+ return nil, err+ }+ p, err := buildProviderFromConfig(ProviderType(provider), config)+ if err != nil {+ return nil, err+ }+ return testConnectionWithProvider(ctx, p)+}++func testConnectionWithProvider(ctx context.Context, provider SandboxProvider) (map[string]any, error) {+ if provider == nil {+ return nil, errors.New("sandbox: provider is nil")+ }+ if err := provider.Initialize(ctx); err != nil {+ return nil, fmt.Errorf("sandbox: initialize provider: %w", err)+ }++ inst, err := provider.CreateInstance(ctx, "python")+ if err != nil {+ return nil, fmt.Errorf("sandbox: create instance: %w", err)+ }+ if inst == nil {+ return nil, errors.New("sandbox: create instance returned no result")+ }+ defer func() {+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)+ defer cancel()+ if err := provider.DestroyInstance(cleanupCtx, inst); err != nil {+ // Do not include provider configuration or upstream error material.+ log.Printf("sandbox connection probe cleanup failed: provider=%s", provider.ProviderType())+ }+ }()++ execCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ result, err := provider.ExecuteCode(execCtx, inst, connectionProbeCode, "python", 10, nil)+ if err != nil {+ return nil, fmt.Errorf("sandbox: execute probe: %w", err)+ }+ if result == nil {+ return nil, errors.New("sandbox: execute probe returned no result")+ }++ success := result.ExitCode == 0 && strings.Contains(result.Stdout, "TEST_PASSED")+ status := "FAILED"+ if success {+ status = "PASSED"+ }+ messageParts := []string{+ "Test " + status,+ fmt.Sprintf("Exit code: %d", result.ExitCode),+ fmt.Sprintf("Execution time: %.2fs", result.ExecutionTime),+ }+ if strings.TrimSpace(result.Stdout) != "" {+ messageParts = append(messageParts, "Output: "+preview(result.Stdout)+"...")+ }+ if strings.TrimSpace(result.Stderr) != "" {+ messageParts = append(messageParts, "Errors: "+preview(result.Stderr)+"...")+ }+ response := map[string]any{+ "success": success,+ "message": strings.Join(messageParts, " | "),+ "details": map[string]any{+ "exit_code": result.ExitCode,+ "execution_time": result.ExecutionTime,+ "stdout": result.Stdout,+ "stderr": result.Stderr,+ },+ }+ return response, nil+}++func preview(value string) string {+ runes := []rune(strings.TrimSpace(value))+ return string(runes[:min(200, len(runes))])+}diff --git a/internal/agent/sandbox/ssh.go b/internal/agent/sandbox/ssh.goindex 4f5d17e22b..04e24a3fa4 100644--- a/internal/agent/sandbox/ssh.go+++ b/internal/agent/sandbox/ssh.go@@ -50,6 +50,7 @@ import ("net""os""path"+ "path/filepath""ragflow/internal/common""strconv""strings"@@ -91,6 +92,7 @@ type SSHProvider struct {maxArtifacts intmaxArtifactBytes intknownHosts string+ configError errormu sync.Mutexinstances map[string]*sshInstance@@ -112,52 +114,52 @@ func newSSHProviderFromEnv() *SSHProvider {}// sshConfigFromEnv builds a config map from the SSH_* env vars.-// PRIVATE_KEY is the literal key contents; PRIVATE_KEY_PATH is-// a path on disk (read at provider-init time). KNOWN_HOSTS is the+// PRIVATE_KEY is either literal key contents or a path on disk.+// KNOWN_HOSTS is the// path to an OpenSSH-format known_hosts file used to verify the-// remote host's key (fail-closed when unset).+// remote host's key, in addition to ~/.ssh/known_hosts.func sshConfigFromEnv() map[string]any {+ privateKey := common.GetEnv(common.EnvSSHPrivateKey)+ if privateKey == "" {+ privateKey = common.GetEnv(common.EnvSSHPrivateKeyPath)+ }return map[string]any{- "HOST": common.GetEnv(common.EnvSSHHost),- "PORT": common.GetEnv(common.EnvSSHPort),- "USERNAME": common.GetEnv(common.EnvSSHUsername),- "PASSWORD": common.GetEnv(common.EnvSSHPassword),- "PRIVATE_KEY": common.GetEnv(common.EnvSSHPrivateKey),- "PRIVATE_KEY_PATH": common.GetEnv(common.EnvSSHPrivateKeyPath),- "PASSPHRASE": common.GetEnv(common.EnvSSHPassphrase),- "PYTHON_BIN": common.GetEnv(common.EnvSSHPythonBin),- "NODE_BIN": common.GetEnv(common.EnvSSHNodeBin),- "WORK_DIR": common.GetEnv(common.EnvSSHWorkDir),- "TIMEOUT": common.GetEnv(common.EnvSSHTimeout),- "MAX_OUTPUT_BYTES": common.GetEnv(common.EnvSSHMaxOutputBytes),- "MAX_ARTIFACTS": common.GetEnv(common.EnvSSHMaxArtifacts),- "MAX_ARTIFACT_BYTES": common.GetEnv(common.EnvSSHMaxArtifactBytes),- "KNOWN_HOSTS": common.GetEnv(common.EnvSSHKnownHosts),+ "host": common.GetEnv(common.EnvSSHHost),+ "port": common.GetEnv(common.EnvSSHPort),+ "username": common.GetEnv(common.EnvSSHUsername),+ "password": common.GetEnv(common.EnvSSHPassword),+ "private_key": privateKey,+ "passphrase": common.GetEnv(common.EnvSSHPassphrase),+ "python_bin": common.GetEnv(common.EnvSSHPythonBin),+ "node_bin": common.GetEnv(common.EnvSSHNodeBin),+ "work_dir": common.GetEnv(common.EnvSSHWorkDir),+ "timeout": common.GetEnv(common.EnvSSHTimeout),+ "max_output_bytes": common.GetEnv(common.EnvSSHMaxOutputBytes),+ "max_artifacts": common.GetEnv(common.EnvSSHMaxArtifacts),+ "max_artifact_bytes": common.GetEnv(common.EnvSSHMaxArtifactBytes),+ "known_hosts": common.GetEnv(common.EnvSSHKnownHosts),}}// newSSHProviderFromConfig builds the provider from a JSON config-// map. Config keys mirror the env-var names without the SSH_-// prefix. PRIVATE_KEY is the literal key contents (preferred);-// PRIVATE_KEY_PATH is a filesystem path (loaded here, like the-// env path). KNOWN_HOSTS is the path to a known_hosts file used-// to verify the remote host key (required for security; the dial-// fails closed when unset).+// map. Config keys use the lowercase Python schema names.+// private_key is either literal key contents or a filesystem path.+// known_hosts adds trusted host keys to ~/.ssh/known_hosts.func newSSHProviderFromConfig(cfg map[string]any) *SSHProvider {p := &SSHProvider{- host: configString(cfg, "HOST"),- port: configInt(cfg, "PORT", sshDefaultPort),- username: configString(cfg, "USERNAME"),- password: configString(cfg, "PASSWORD"),- passphrase: configString(cfg, "PASSPHRASE"),- pythonBin: configString(cfg, "PYTHON_BIN"),- nodeBin: configString(cfg, "NODE_BIN"),- workDir: configString(cfg, "WORK_DIR"),- timeout: configInt(cfg, "TIMEOUT", sshDefaultTimeout),- maxOutputBytes: configInt(cfg, "MAX_OUTPUT_BYTES", sshDefaultMaxOutput),- maxArtifacts: configInt(cfg, "MAX_ARTIFACTS", sshDefaultMaxArtifacts),- maxArtifactBytes: configInt(cfg, "MAX_ARTIFACT_BYTES", sshDefaultMaxArtifact),- knownHosts: configString(cfg, "KNOWN_HOSTS"),+ host: configString(cfg, "host"),+ port: configInt(cfg, "port", sshDefaultPort),+ username: configString(cfg, "username"),+ password: configString(cfg, "password"),+ passphrase: configString(cfg, "passphrase"),+ pythonBin: configString(cfg, "python_bin"),+ nodeBin: configString(cfg, "node_bin"),+ workDir: configString(cfg, "work_dir"),+ timeout: configInt(cfg, "timeout", sshDefaultTimeout),+ maxOutputBytes: configInt(cfg, "max_output_bytes", sshDefaultMaxOutput),+ maxArtifacts: configInt(cfg, "max_artifacts", sshDefaultMaxArtifacts),+ maxArtifactBytes: configInt(cfg, "max_artifact_bytes", sshDefaultMaxArtifact),+ knownHosts: configString(cfg, "known_hosts"),instances: map[string]*sshInstance{},}if p.pythonBin == "" {@@ -169,12 +171,12 @@ func newSSHProviderFromConfig(cfg map[string]any) *SSHProvider {if p.workDir == "" {p.workDir = sshDefaultWorkDir}- // Private key: prefer the literal content if set; otherwise- // read from the path.- if v := configString(cfg, "PRIVATE_KEY"); v != "" {- p.privateKey = []byte(v)- } else if keyPath := configString(cfg, "PRIVATE_KEY_PATH"); keyPath != "" {- if b, err := os.ReadFile(keyPath); err == nil {+ if v := configString(cfg, "private_key"); strings.TrimSpace(v) != "" {+ if strings.Contains(v, "-----BEGIN ") {+ p.privateKey = []byte(v)+ } else if b, err := os.ReadFile(strings.TrimSpace(v)); err != nil {+ p.configError = fmt.Errorf("ssh: read private_key path %q: %w", v, err)+ } else {p.privateKey = b}}@@ -191,6 +193,9 @@ func (p *SSHProvider) ProviderType() ProviderType { return ProviderSSH }// a connection here — connectivity is verified by HealthCheck// and by CreateInstance.func (p *SSHProvider) Initialize(ctx context.Context) error {+ if p.configError != nil {+ return p.configError+ }if p.host == "" {return errors.New("ssh: SSH_HOST env var is required")}@@ -431,7 +436,13 @@ func (p *SSHProvider) isInitialized() bool {func (p *SSHProvider) dial(ctx context.Context) (*ssh.Client, error) {auth := []ssh.AuthMethod{}if len(p.privateKey) > 0 {- signer, err := ssh.ParsePrivateKey(p.privateKey)+ var signer ssh.Signer+ var err error+ if p.passphrase != "" {+ signer, err = ssh.ParsePrivateKeyWithPassphrase(p.privateKey, []byte(p.passphrase))+ } else {+ signer, err = ssh.ParsePrivateKey(p.privateKey)+ }if err != nil {return nil, fmt.Errorf("ssh: parse private key: %w", err)}@@ -493,14 +504,19 @@ func (p *SSHProvider) dial(ctx context.Context) (*ssh.Client, error) {}// hostKeyCallback builds an ssh.HostKeyCallback backed by an OpenSSH-// known_hosts file. The provider fails closed when no known_hosts-// path is configured: this protects against man-in-the-middle attacks-// on the SSH transport used to run sandboxed code.+// known_hosts files. Unknown host keys are always rejected.func (p *SSHProvider) hostKeyCallback() (ssh.HostKeyCallback, error) {- if p.knownHosts == "" {- return nil, errors.New("ssh: KNOWN_HOSTS not configured; refusing to connect without host key verification (set SSH_KNOWN_HOSTS)")+ var files []string+ if home, err := os.UserHomeDir(); err == nil {+ file := filepath.Join(home, ".ssh", "known_hosts")+ if _, err := os.Stat(file); err == nil {+ files = append(files, file)+ }+ }+ if p.knownHosts != "" {+ files = append(files, p.knownHosts)}- callback, err := knownhosts.New(p.knownHosts)+ callback, err := knownhosts.New(files...)if err != nil {return nil, fmt.Errorf("ssh: load known_hosts %q: %w", p.knownHosts, err)}diff --git a/internal/agent/sandbox/ssh_test.go b/internal/agent/sandbox/ssh_test.goindex 41e83cd325..697f2d8bc7 100644--- a/internal/agent/sandbox/ssh_test.go+++ b/internal/agent/sandbox/ssh_test.go@@ -18,6 +18,14 @@ package sandboximport ("context"+ "crypto/ed25519"+ "crypto/rand"+ "encoding/pem"+ "fmt"+ "path/filepath"++ "golang.org/x/crypto/ssh"+ "golang.org/x/crypto/ssh/knownhosts""net""os""strconv"@@ -101,6 +109,41 @@ func TestSSH_PrivateKeyInline(t *testing.T) {}}+func TestSSH_ConfigUsesCanonicalLowercaseKeys(t *testing.T) {+ p := newSSHProviderFromConfig(map[string]any{+ "host": "example.test", "username": "u", "password": "p",+ "port": 2222, "timeout": 12, "private_key": "-----BEGIN RSA PRIVATE KEY-----\nfake\n-----END RSA PRIVATE KEY-----",+ })+ if p.host != "example.test" || p.port != 2222 || p.timeout != 12 {+ t.Fatalf("lowercase config was not applied: %#v", p)+ }+ legacy := newSSHProviderFromConfig(map[string]any{"HOST": "legacy", "USERNAME": "u", "PASSWORD": "p"})+ if legacy.host != "" {+ t.Fatalf("uppercase configuration unexpectedly accepted: %q", legacy.host)+ }+}++func TestSSH_PrivateKeyPathError(t *testing.T) {+ p := newSSHProviderFromConfig(map[string]any{+ "host": "h", "username": "u", "private_key": t.TempDir() + "/missing",+ })+ if err := p.Initialize(t.Context()); err == nil || !strings.Contains(err.Error(), "read private_key path") {+ t.Fatalf("Initialize error = %v, want explicit private key path error", err)+ }+}++func TestSSH_ConfigPrivateKeyPath(t *testing.T) {+ keyPath := t.TempDir() + "/private_key"+ key := "-----BEGIN OPENSSH PRIVATE KEY-----\ncontent\n-----END OPENSSH PRIVATE KEY-----\n"+ if err := os.WriteFile(keyPath, []byte(key), 0o600); err != nil {+ t.Fatal(err)+ }+ p := newSSHProviderFromConfig(map[string]any{"host": "h", "username": "u", "private_key": keyPath})+ if p.configError != nil || string(p.privateKey) != key {+ t.Fatalf("private_key path was not loaded: %v", p.configError)+ }+}+func TestSSH_Initialize_MissingHost(t *testing.T) {ctx := t.Context()t.Setenv("SSH_HOST", "")@@ -286,3 +329,82 @@ func TestMinTimeout(t *testing.T) {t.Errorf("minTimeout(0, 5) = %d, want 1 (floor is 1)", got)}}++func TestSSHEncryptedKeyAndDefaultHostKeys(t *testing.T) {+ _, key, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ signer, err := ssh.NewSignerFromKey(key)+ if err != nil {+ t.Fatal(err)+ }+ block, err := ssh.MarshalPrivateKeyWithPassphrase(key, "test", []byte("secret"))+ if err != nil {+ t.Fatal(err)+ }+ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer listener.Close()+ serverConfig := &ssh.ServerConfig{PublicKeyCallback: func(_ ssh.ConnMetadata, presented ssh.PublicKey) (*ssh.Permissions, error) {+ if string(presented.Marshal()) != string(signer.PublicKey().Marshal()) {+ return nil, fmt.Errorf("unexpected authentication key")+ }+ return nil, nil+ }}+ serverConfig.AddHostKey(signer)+ serverErr := make(chan error, 1)+ go func() {+ conn, err := listener.Accept()+ if err != nil {+ serverErr <- err+ return+ }+ defer conn.Close()+ server, _, _, err := ssh.NewServerConn(conn, serverConfig)+ if err == nil {+ defer server.Close()+ }+ serverErr <- err+ }()+ home := t.TempDir()+ t.Setenv("HOME", home)+ if err := os.Mkdir(filepath.Join(home, ".ssh"), 0o700); err != nil {+ t.Fatal(err)+ }+ hostKeys := filepath.Join(home, ".ssh", "known_hosts")+ if err := os.WriteFile(hostKeys, []byte(knownhosts.Line([]string{listener.Addr().String()}, signer.PublicKey())+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ host, port, _ := net.SplitHostPort(listener.Addr().String())+ p := newSSHProviderFromConfig(map[string]any{"host": host, "port": port, "username": "test", "private_key": string(pem.EncodeToMemory(block)), "passphrase": "secret"})+ client, err := p.dial(t.Context())+ if err != nil {+ t.Fatal(err)+ }+ client.Close()+ if err := <-serverErr; err != nil {+ t.Fatal(err)+ }+ p.passphrase = "incorrect"+ if _, err := p.dial(t.Context()); err == nil || !strings.Contains(err.Error(), "parse private key") {+ t.Fatalf("wrong passphrase: %v", err)+ }+ p.knownHosts = filepath.Join(home, "missing")+ if _, err := p.hostKeyCallback(); err == nil {+ t.Fatal("unreadable explicit trust store accepted")+ }+ p.knownHosts = ""+ if err := os.Remove(hostKeys); err != nil {+ t.Fatal(err)+ }+ callback, err := p.hostKeyCallback()+ if err != nil {+ t.Fatal(err)+ }+ if err := callback(listener.Addr().String(), listener.Addr(), signer.PublicKey()); err == nil {+ t.Fatal("unknown host accepted")+ }+}diff --git a/internal/agent/sandbox/tenki.go b/internal/agent/sandbox/tenki.goindex a64f30b711..4337cddfc3 100644--- a/internal/agent/sandbox/tenki.go+++ b/internal/agent/sandbox/tenki.go@@ -24,8 +24,8 @@//// The code-wrapping protocol is shared with SelfManaged, Aliyun and// e2b, so the `__RAGFLOW_RESULT__:` marker extraction works uniformly.-// Like the Go e2b provider, this port does not collect run artifacts-// (artifact collection lives only in the local/ssh providers).+// Artifacts are collected from a per-instance workspace using the same+// allowlist and result shape as the local/ssh providers.//// SDK: github.com/LuxorLabs/tenki-sdk-go/sandbox (MIT). The auth// token and API URL are read from env by Initialize; image and@@ -36,31 +36,54 @@ package sandboximport ("context"+ "encoding/base64""errors""fmt"+ "mime"+ "path""ragflow/internal/common"+ "slices"+ "strings""sync""time"tenkisdk "github.com/LuxorLabs/tenki-sdk-go/sandbox")-// tenkiDefaultSandboxTimeout bounds a single CodeExec call. A fresh-// sandbox is provisioned per CreateInstance and destroyed on-// DestroyInstance, so the lifetime need only outlast one execution.-const tenkiDefaultSandboxTimeout = 5 * time.Minute+const (+ tenkiDefaultTimeout = 30 * time.Second+ tenkiDefaultMaxLifetime = time.Hour+ tenkiMaxArtifactDepth = 16+ tenkiDefaultMaxOutput = 1 << 20+ tenkiDefaultMaxArtifacts = 20+ tenkiDefaultArtifactBytes = 10 << 20+)++type tenkiInstance struct {+ session *tenkisdk.Session+ remoteWorkDir string+}// TenkiProvider is the Go port of the Python TenkiProvider.type TenkiProvider struct {- client *tenkisdk.Client- apiKey string- apiURL string- image string- allowOutbound bool- sandboxTimeout time.Duration+ client *tenkisdk.Client+ apiKey string+ baseURL string+ image string+ allowOutbound bool+ timeout time.Duration+ maxLifetime time.Duration+ cpuCores int+ memoryMB int+ diskSizeGB int+ maxOutputBytes int+ maxArtifacts int+ maxArtifactBytes intmu sync.Mutexinitialized bool+ instancesMu sync.Mutex+ instances map[string]tenkiInstance}// newTenkiProviderFromEnv reads TENKI_* env vars and returns a@@ -73,11 +96,11 @@ func newTenkiProviderFromEnv() *TenkiProvider {// mirroring the admin-panel settings JSON shape.func tenkiConfigFromEnv() map[string]any {return map[string]any{- "API_KEY": common.GetEnv(common.EnvTenkiAPIKey),- "API_URL": common.GetEnv(common.EnvTenkiAPIURL),- "IMAGE": common.GetEnv(common.EnvTenkiImage),- "TIMEOUT": common.GetEnv(common.EnvTenkiTimeout),- "ALLOW_OUTBOUND": common.GetEnv(common.EnvTenkiAllowOutbound),+ "api_key": common.GetEnv(common.EnvTenkiAPIKey),+ "base_url": common.GetEnv(common.EnvTenkiAPIURL),+ "image": common.GetEnv(common.EnvTenkiImage),+ "timeout": common.GetEnv(common.EnvTenkiTimeout),+ "allow_outbound": common.GetEnv(common.EnvTenkiAllowOutbound),}}@@ -85,20 +108,23 @@ func tenkiConfigFromEnv() map[string]any {// map (admin-panel settings or the env-backed map above).func newTenkiProviderFromConfig(cfg map[string]any) *TenkiProvider {p := &TenkiProvider{- apiKey: configString(cfg, "API_KEY"),- apiURL: configString(cfg, "API_URL"),- image: configString(cfg, "IMAGE"),+ apiKey: configString(cfg, "api_key"),+ baseURL: configString(cfg, "base_url"),+ image: configString(cfg, "image"),// Outbound network is opt-in: sandboxed code has no egress// unless ALLOW_OUTBOUND is explicitly "true". This matches// the self_managed sandbox, which treats network access as an// unauthorized-access event by default.- allowOutbound: configString(cfg, "ALLOW_OUTBOUND") == "true",- }- timeoutSec := configInt(cfg, "TIMEOUT", int(tenkiDefaultSandboxTimeout.Seconds()))- if timeoutSec > 0 {- p.sandboxTimeout = time.Duration(timeoutSec) * time.Second- } else {- p.sandboxTimeout = tenkiDefaultSandboxTimeout+ allowOutbound: configString(cfg, "allow_outbound") == "true",+ timeout: time.Duration(configInt(cfg, "timeout", int(tenkiDefaultTimeout/time.Second))) * time.Second,+ maxLifetime: time.Duration(configInt(cfg, "max_lifetime", int(tenkiDefaultMaxLifetime/time.Second))) * time.Second,+ cpuCores: configInt(cfg, "cpu_cores", 0),+ memoryMB: configInt(cfg, "memory_mb", 0),+ diskSizeGB: configInt(cfg, "disk_size_gb", 0),+ maxOutputBytes: configInt(cfg, "max_output_bytes", tenkiDefaultMaxOutput),+ maxArtifacts: configInt(cfg, "max_artifacts", tenkiDefaultMaxArtifacts),+ maxArtifactBytes: configInt(cfg, "max_artifact_bytes", tenkiDefaultArtifactBytes),+ instances: make(map[string]tenkiInstance),}return p}@@ -117,13 +143,16 @@ func (p *TenkiProvider) Initialize(ctx context.Context) error {if apiKey == "" {return errors.New("tenki: API key is required (set it in Admin > Sandbox Settings or TENKI_API_KEY)")}- apiURL := p.apiURL- if apiURL == "" {- apiURL = common.GetEnv(common.EnvTenkiAPIURL)+ baseURL := p.baseURL+ if baseURL == "" {+ baseURL = common.GetEnv(common.EnvTenkiAPIURL)}opts := []tenkisdk.Option{tenkisdk.WithAuthToken(apiKey)}- if apiURL != "" {- opts = append(opts, tenkisdk.WithBaseURL(apiURL))+ if p.timeout > 0 {+ opts = append(opts, tenkisdk.WithHTTPTimeout(p.timeout))+ }+ if baseURL != "" {+ opts = append(opts, tenkisdk.WithBaseURL(baseURL))}c, err := tenkisdk.New(opts...)if err != nil {@@ -156,8 +185,18 @@ func (p *TenkiProvider) CreateInstance(ctx context.Context, template string) (*S}opts := []tenkisdk.CreateOption{tenkisdk.WithAllowOutbound(p.allowOutbound),- tenkisdk.WithMaxDuration(p.sandboxTimeout),- tenkisdk.WithWaitTimeout(p.sandboxTimeout),+ tenkisdk.WithMaxDuration(p.maxLifetime),+ tenkisdk.WithWaitTimeout(p.timeout),+ tenkisdk.WithMetadata(map[string]string{"source": "ragflow"}),+ }+ if p.cpuCores > 0 {+ opts = append(opts, tenkisdk.WithCPUCores(int32(p.cpuCores)))+ }+ if p.memoryMB > 0 {+ opts = append(opts, tenkisdk.WithMemoryMB(int32(p.memoryMB)))+ }+ if p.diskSizeGB > 0 {+ opts = append(opts, tenkisdk.WithDiskSizeGB(p.diskSizeGB))}if p.image != "" {opts = append(opts, tenkisdk.WithImage(p.image))@@ -166,14 +205,27 @@ func (p *TenkiProvider) CreateInstance(ctx context.Context, template string) (*Sif err != nil {return nil, fmt.Errorf("tenki: Create: %w", err)}+ remoteWorkDir := tenkiWorkspacePath(sess.ID)+ if err := sess.Mkdir(ctx, path.Join(remoteWorkDir, "artifacts")); err != nil {+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)+ _ = sess.Close(cleanupCtx)+ cancel()+ return nil, fmt.Errorf("tenki: create workspace: %w", err)+ }+ instanceID := sess.ID+ p.instancesMu.Lock()+ p.instances[instanceID] = tenkiInstance{session: sess, remoteWorkDir: remoteWorkDir}+ p.instancesMu.Unlock()return &SandboxInstance{- InstanceID: sess.ID,+ InstanceID: instanceID,Provider: ProviderTenki,Status: "running",Metadata: map[string]any{"language": lang,"image": p.image,- "sandbox_timeout": p.sandboxTimeout.String(),+ "remote_work_dir": remoteWorkDir,+ "max_lifetime": p.maxLifetime.String(),+ "timeout": p.timeout.String(),},}, nil}@@ -199,13 +251,14 @@ func (p *TenkiProvider) ExecuteCode(if lang == "" {return nil, fmt.Errorf("tenki: unsupported language %q", language)}+ if timeoutSec == 0 {+ timeoutSec = int(p.timeout.Seconds())+ }timeout, err := validateTimeout(timeoutSec)if err != nil {return nil, err}- if timeout == 0 {- timeout = int(p.sandboxTimeout.Seconds())- }+ timeout = min(timeout, int(p.timeout.Seconds()))argsJSON, err := argsToJSON(args)if err != nil {@@ -223,19 +276,18 @@ func (p *TenkiProvider) ExecuteCode(runArgs = []string{"-e", wrapped}}- // Re-obtain a handle to the sandbox created in CreateInstance and- // wait for its data plane to be ready before exec.- sess, err := p.client.Session(inst.InstanceID)- if err != nil {- return nil, fmt.Errorf("tenki: Session(%s): %w", inst.InstanceID, err)- }- if err := sess.WaitReady(ctx, p.sandboxTimeout); err != nil {- return nil, fmt.Errorf("tenki: WaitReady(%s): %w", inst.InstanceID, err)+ p.instancesMu.Lock()+ instance, ok := p.instances[inst.InstanceID]+ p.instancesMu.Unlock()+ if !ok || instance.session == nil {+ return nil, fmt.Errorf("tenki: unknown instance %q", inst.InstanceID)}+ sess := instance.sessionstart := time.Now()res, err := sess.Exec(ctx, cmd,tenkisdk.WithArgs(runArgs...),+ tenkisdk.WithDir(instance.remoteWorkDir),tenkisdk.WithTimeout(time.Duration(timeout)*time.Second),)if err != nil {@@ -245,7 +297,18 @@ func (p *TenkiProvider) ExecuteCode(// runArgs — they embed the user's code and arguments.return nil, fmt.Errorf("tenki: exec %s: %w", cmd, err)}- return buildTenkiExecutionResult(res, lang, start), nil+ if outputErr := validateTenkiOutputSize(string(res.Stdout), string(res.Stderr), p.maxOutputBytes); outputErr != nil {+ return nil, outputErr+ }+ result := buildTenkiExecutionResult(res, lang, start)+ artifacts, artifactErr := p.collectArtifacts(ctx, sess, path.Join(instance.remoteWorkDir, "artifacts"), 0)+ if artifactErr != nil {+ return nil, fmt.Errorf("tenki: collect artifacts: %w", artifactErr)+ }+ result.Metadata["artifacts"] = artifacts+ result.Metadata["remote_work_dir"] = instance.remoteWorkDir+ result.Metadata["timeout"] = timeout+ return result, nil}// buildTenkiExecutionResult maps the Tenki Result to our@@ -277,10 +340,16 @@ func (p *TenkiProvider) DestroyInstance(ctx context.Context, inst *SandboxInstanif inst == nil || inst.InstanceID == "" {return fmt.Errorf("tenki: instance id required")}- sess, err := p.client.Session(inst.InstanceID)- if err != nil {- return fmt.Errorf("tenki: Session(%s): %w", inst.InstanceID, err)+ p.instancesMu.Lock()+ instance, ok := p.instances[inst.InstanceID]+ if ok {+ delete(p.instances, inst.InstanceID)+ }+ p.instancesMu.Unlock()+ if !ok || instance.session == nil {+ return nil}+ sess := instance.sessionif err := sess.Close(ctx); err != nil {if errors.Is(err, tenkisdk.ErrSessionNotFound) ||errors.Is(err, tenkisdk.ErrSessionTerminated) ||@@ -309,3 +378,93 @@ func (p *TenkiProvider) isInitialized() bool {defer p.mu.Unlock()return p.initialized}++func validateTenkiOutputSize(stdout, stderr string, maxBytes int) error {+ if maxBytes > 0 && len(stdout)+len(stderr) > maxBytes {+ return fmt.Errorf("tenki: output exceeds %d bytes", maxBytes)+ }+ return nil+}++func tenkiWorkspacePath(sessionID string) string {+ return path.Join("/home/tenki", "ragflow-codeexec-"+sessionID)+}++func (p *TenkiProvider) collectArtifacts(ctx context.Context, sess *tenkisdk.Session, currentDir string, depth int) ([]map[string]any, error) {+ return p.collectArtifactsRecursive(ctx, sess, currentDir, "", depth, nil)+}++func (p *TenkiProvider) collectArtifactsRecursive(ctx context.Context, sess *tenkisdk.Session, currentDir, relativeDir string, depth int, artifacts []map[string]any) ([]map[string]any, error) {+ if depth > tenkiMaxArtifactDepth {+ return nil, fmt.Errorf("artifact directory nesting exceeds %d levels: %s", tenkiMaxArtifactDepth, currentDir)+ }+ entries, err := sess.List(ctx, currentDir)+ if errors.Is(err, tenkisdk.ErrFileNotFound) {+ return artifacts, nil+ }+ if err != nil {+ return nil, err+ }+ slices.SortFunc(entries, func(a, b tenkisdk.FileInfo) int {+ return strings.Compare(a.Path, b.Path)+ })++ if artifacts == nil {+ artifacts = make([]map[string]any, 0, len(entries))+ }+ for _, entry := range entries {+ name := path.Base(entry.Path)+ if name == "." || name == ".." || entry.Path != name {+ return nil, fmt.Errorf("tenki: invalid artifact entry name: %s", entry.Path)+ }+ remotePath := path.Join(currentDir, name)+ relativePath := path.Join(relativeDir, name)+ // List does not populate IsSymlink in this SDK; Mode uses POSIX bits.+ if entry.IsSymlink || entry.Mode&0o170000 == 0o120000 {+ return nil, fmt.Errorf("artifact symlinks are not allowed: %s", relativePath)+ }+ info, statErr := sess.Stat(ctx, remotePath)+ if statErr != nil {+ return nil, statErr+ }+ if info.IsSymlink || info.Mode&0o170000 == 0o120000 {+ return nil, fmt.Errorf("artifact symlinks are not allowed: %s", relativePath)+ }+ if entry.IsDir {+ nested, nestedErr := p.collectArtifactsRecursive(ctx, sess, remotePath, relativePath, depth+1, artifacts)+ if nestedErr != nil {+ return nil, nestedErr+ }+ artifacts = nested+ continue+ }+ if len(artifacts) >= p.maxArtifacts {+ return nil, fmt.Errorf("tenki: execution produced more than %d artifacts", p.maxArtifacts)+ }+ if entry.Size > int64(p.maxArtifactBytes) {+ return nil, fmt.Errorf("tenki: artifact exceeds %d bytes: %s", p.maxArtifactBytes, relativePath)+ }+ ext := strings.ToLower(path.Ext(name))+ if _, ok := allowedArtifactExts[ext]; !ok {+ return nil, fmt.Errorf("tenki: unsupported artifact type: %s", relativePath)+ }+ content, readErr := sess.ReadFile(ctx, remotePath)+ if readErr != nil {+ return nil, readErr+ }+ if len(content) > p.maxArtifactBytes {+ return nil, fmt.Errorf("tenki: artifact exceeds %d bytes: %s", p.maxArtifactBytes, relativePath)+ }+ mimeType := mime.TypeByExtension(ext)+ if mimeType == "" {+ mimeType = "application/octet-stream"+ }+ artifacts = append(artifacts, map[string]any{+ "name": relativePath,+ "content_b64": base64.StdEncoding.EncodeToString(content),+ "mime_type": mimeType,+ "size": int64(len(content)),+ })+ }+ return artifacts, nil+}diff --git a/internal/agent/sandbox/tenki_test.go b/internal/agent/sandbox/tenki_test.goindex 90d911af08..a3acf0d14a 100644--- a/internal/agent/sandbox/tenki_test.go+++ b/internal/agent/sandbox/tenki_test.go@@ -18,7 +18,6 @@ package sandboximport ("context"- "ragflow/internal/common""strings""testing""time"@@ -59,8 +58,8 @@ func TestTenkiProvider_Defaults(t *testing.T) {if p.image != "" {t.Errorf("image = %q, want empty (SDK default image)", p.image)}- if p.sandboxTimeout != tenkiDefaultSandboxTimeout {- t.Errorf("sandboxTimeout = %v, want %v", p.sandboxTimeout, tenkiDefaultSandboxTimeout)+ if p.timeout != tenkiDefaultTimeout || p.maxLifetime != tenkiDefaultMaxLifetime {+ t.Errorf("timeouts = execution:%v lifetime:%v, want execution:%v lifetime:%v", p.timeout, p.maxLifetime, tenkiDefaultTimeout, tenkiDefaultMaxLifetime)}if p.allowOutbound {t.Errorf("allowOutbound = true, want false by default (network is opt-in)")@@ -75,14 +74,51 @@ func TestTenkiProvider_EnvOverride(t *testing.T) {if p.image != "custom-image" {t.Errorf("image = %q, want %q", p.image, "custom-image")}- if p.sandboxTimeout != 120*time.Second {- t.Errorf("sandboxTimeout = %v, want 120s", p.sandboxTimeout)+ if p.timeout != 120*time.Second {+ t.Errorf("timeout = %v, want 120s", p.timeout)}if !p.allowOutbound {t.Errorf("allowOutbound = false, want true when TENKI_ALLOW_OUTBOUND=true")}}+func TestTenkiProvider_ConfigUsesCanonicalKeysAndLimits(t *testing.T) {+ p := newTenkiProviderFromConfig(map[string]any{+ "api_key": "tk_test",+ "base_url": "https://example.test",+ "timeout": "45",+ "max_lifetime": "600",+ "cpu_cores": 4,+ "memory_mb": 4096,+ "disk_size_gb": 10,+ "max_output_bytes": 2048,+ "max_artifacts": 3,+ "max_artifact_bytes": 4096,+ })+ if p.apiKey != "tk_test" || p.baseURL != "https://example.test" {+ t.Fatalf("canonical config was not loaded: api_key=%q base_url=%q", p.apiKey, p.baseURL)+ }+ if p.timeout != 45*time.Second || p.maxLifetime != 10*time.Minute {+ t.Fatalf("timeouts = execution:%v lifetime:%v", p.timeout, p.maxLifetime)+ }+ if p.cpuCores != 4 || p.memoryMB != 4096 || p.diskSizeGB != 10 ||+ p.maxOutputBytes != 2048 || p.maxArtifacts != 3 || p.maxArtifactBytes != 4096 {+ t.Fatalf("resource limits were not loaded: %+v", p)+ }+ if legacy := newTenkiProviderFromConfig(map[string]any{"API_KEY": "legacy", "TIMEOUT": 7}); legacy.apiKey != "" || legacy.timeout != tenkiDefaultTimeout {+ t.Fatalf("uppercase compatibility keys must not be accepted: %+v", legacy)+ }+}++func TestTenkiProvider_OutputCapCountsRawBytes(t *testing.T) {+ if err := validateTenkiOutputSize("é", "x", 2); err == nil {+ t.Fatal("expected UTF-8 output to be rejected by byte cap")+ }+ if err := validateTenkiOutputSize("ok", "x", 3); err != nil {+ t.Fatalf("unexpected output-cap error: %v", err)+ }+}+// TestTenkiProvider_Initialize_MissingCreds verifies the provider// refuses to initialize when TENKI_API_KEY is unset.func TestTenkiProvider_Initialize_MissingCreds(t *testing.T) {@@ -162,7 +198,7 @@ func TestTenkiProvider_ExecuteCode_RejectsBadInputs(t *testing.T) {name: "timeout too small",fn: func() error {_, err := p.ExecuteCode(t.Context(),- &SandboxInstance{InstanceID: "x"}, "x", "python", 0, nil)+ &SandboxInstance{InstanceID: "x"}, "x", "python", -1, nil)return err},want: "timeout",@@ -237,42 +273,6 @@ func TestTenkiProvider_BuildTenkiExecutionResult(t *testing.T) {}}-// TestTenkiProvider_FullE2E_SkipWithoutKey is the integration test-// path. The body is skipped unless TENKI_API_KEY is set, but the test-// always runs (so missing-secrets shows up in CI logs). When enabled,-// it creates a real sandbox, runs Python, and destroys it.-func TestTenkiProvider_FullE2E_SkipWithoutKey(t *testing.T) {- apiKey := common.GetEnv(common.EnvTenkiAPIKey)- if apiKey == "" {- t.Skip("TENKI_API_KEY not set — skipping full E2E test (real network call)")- }- p := newTenkiProviderFromEnv()- ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)- defer cancel()- if err := p.Initialize(ctx); err != nil {- t.Fatalf("Initialize: %v", err)- }- inst, err := p.CreateInstance(ctx, "python")- if err != nil {- t.Fatalf("CreateInstance: %v", err)- }- defer func() {- cleanupCtx, cleanupCancel := context.WithTimeout(t.Context(), 30*time.Second)- defer cleanupCancel()- if err := p.DestroyInstance(cleanupCtx, inst); err != nil {- t.Errorf("DestroyInstance: %v", err)- }- }()-- result, err := p.ExecuteCode(ctx, inst, "def main(): return 1+1", "python", 30, nil)- if err != nil {- t.Fatalf("ExecuteCode: %v", err)- }- if result.ExitCode != 0 {- t.Errorf("ExitCode = %d, want 0; stderr=%q", result.ExitCode, result.Stderr)- }-}-// TestTenkiProvider_ProviderType_StaysDistinct ensures the tenki// provider does not collide on the wire with the other providers.func TestTenkiProvider_ProviderType_StaysDistinct(t *testing.T) {diff --git a/internal/agent/sandbox/testdata/admin_contract.json b/internal/agent/sandbox/testdata/admin_contract.jsonnew file mode 100644index 0000000000..2d28876d5a--- /dev/null+++ b/internal/agent/sandbox/testdata/admin_contract.json@@ -0,0 +1,653 @@+{+ "providers": [+ {+ "id": "local",+ "name": "Local",+ "description": "Execute code directly on the current host process.",+ "tags": [+ "local",+ "host",+ "minimal"+ ]+ },+ {+ "id": "self_managed",+ "name": "Self-Managed",+ "description": "On-premise deployment using Daytona/Docker",+ "tags": [+ "self-hosted",+ "low-latency",+ "secure"+ ]+ },+ {+ "id": "ssh",+ "name": "SSH",+ "description": "Execute code on a remote machine over SSH.",+ "tags": [+ "remote",+ "ssh",+ "custom-runtime"+ ]+ },+ {+ "id": "aliyun_codeinterpreter",+ "name": "Aliyun Code Interpreter",+ "description": "Aliyun Function Compute Code Interpreter - Code execution in serverless microVMs",+ "tags": [+ "saas",+ "cloud",+ "scalable",+ "aliyun"+ ]+ },+ {+ "id": "e2b",+ "name": "E2B",+ "description": "E2B Cloud - Code Execution Sandboxes",+ "tags": [+ "saas",+ "fast",+ "global"+ ]+ },+ {+ "id": "tenki",+ "name": "Tenki",+ "description": "Tenki - Disposable microVM code sandboxes",+ "tags": [+ "saas",+ "cloud",+ "microvm",+ "isolated"+ ]+ },+ {+ "id": "ucloud_agent_sandbox",+ "name": "UCloud Agent Sandbox",+ "description": "UCloud Agent Sandbox - Disposable cloud sandboxes for agent code execution",+ "tags": [+ "saas",+ "cloud",+ "isolated",+ "ucloud"+ ]+ }+ ],+ "schemas": {+ "local": {+ "python_bin": {+ "type": "string",+ "required": false,+ "default": "python3",+ "label": "Python Binary",+ "description": "Python executable used for local code execution."+ },+ "node_bin": {+ "type": "string",+ "required": false,+ "default": "node",+ "label": "Node.js Binary",+ "description": "Node.js executable used for local JavaScript execution."+ },+ "work_dir": {+ "type": "string",+ "required": false,+ "default": "/tmp/ragflow-codeexec",+ "label": "Working Directory",+ "description": "Directory used to store temporary scripts and artifacts on the current host."+ },+ "timeout": {+ "type": "integer",+ "required": false,+ "default": 30,+ "label": "Timeout (seconds)",+ "description": "Maximum execution time for each local run. Unit: seconds.",+ "min": 1,+ "max": 600+ },+ "max_memory_mb": {+ "type": "integer",+ "required": false,+ "default": 512,+ "label": "Max Memory (MB)",+ "description": "Address-space memory limit for the local child process. Unit: MB.",+ "min": 1,+ "max": 65536+ },+ "max_output_bytes": {+ "type": "integer",+ "required": false,+ "default": 1048576,+ "label": "Max Output (bytes)",+ "description": "Maximum combined stdout and stderr size. Unit: bytes.",+ "min": 1024,+ "max": 10485760+ },+ "max_artifacts": {+ "type": "integer",+ "required": false,+ "default": 20,+ "label": "Max Artifacts",+ "description": "Maximum number of files collected from the artifacts directory.",+ "min": 0,+ "max": 100+ },+ "max_artifact_bytes": {+ "type": "integer",+ "required": false,+ "default": 10485760,+ "label": "Max Artifact Size (bytes)",+ "description": "Maximum size of a single artifact file. Unit: bytes.",+ "min": 1024,+ "max": 104857600+ }+ },+ "self_managed": {+ "endpoint": {+ "type": "string",+ "required": true,+ "label": "Executor Manager Endpoint",+ "placeholder": "http://sandbox-executor-manager:9385",+ "default": "http://sandbox-executor-manager:9385",+ "description": "HTTP endpoint used by RAGFlow to call sandbox-executor-manager.",+ "scope": "runtime",+ "readonly": false+ },+ "api_token": {+ "type": "string",+ "required": false,+ "label": "Executor Manager API Token",+ "secret": true,+ "placeholder": "Optional; defaults to SANDBOX_EXECUTOR_MANAGER_API_TOKEN",+ "default": "",+ "description": "Shared secret authenticating RAGFlow to sandbox-executor-manager. Must match SANDBOX_EXECUTOR_MANAGER_API_TOKEN on the executor-manager side.",+ "scope": "runtime",+ "readonly": false+ },+ "timeout": {+ "type": "integer",+ "required": false,+ "label": "Request Timeout (seconds)",+ "default": 30,+ "min": 5,+ "max": 300,+ "description": "Maximum request time for a single code execution call. Unit: seconds.",+ "scope": "runtime",+ "readonly": false+ },+ "executor_manager_image": {+ "type": "string",+ "required": false,+ "label": "Executor Manager Image",+ "default": "infiniflow/sandbox-executor-manager:latest",+ "description": "Docker image used by sandbox-executor-manager.",+ "scope": "deployment",+ "readonly": true+ },+ "executor_manager_pool_size": {+ "type": "integer",+ "required": false,+ "label": "Container Pool Size",+ "default": 3,+ "min": 1,+ "max": 100,+ "description": "Container pool size used by sandbox-executor-manager.",+ "scope": "deployment",+ "readonly": true+ },+ "base_python_image": {+ "type": "string",+ "required": false,+ "label": "Base Python Image",+ "default": "infiniflow/sandbox-base-python:latest",+ "description": "Python runtime image used by executor-managed containers.",+ "scope": "deployment",+ "readonly": true+ },+ "base_nodejs_image": {+ "type": "string",+ "required": false,+ "label": "Base Node.js Image",+ "default": "infiniflow/sandbox-base-nodejs:latest",+ "description": "Node.js runtime image used by executor-managed containers.",+ "scope": "deployment",+ "readonly": true+ },+ "executor_manager_port": {+ "type": "integer",+ "required": false,+ "label": "Executor Manager Port",+ "default": 9385,+ "min": 1,+ "max": 65535,+ "description": "Host port exposed by sandbox-executor-manager.",+ "scope": "deployment",+ "readonly": true+ },+ "enable_seccomp": {+ "type": "boolean",+ "required": false,+ "label": "Enable Seccomp",+ "default": false,+ "description": "Whether sandbox-executor-manager starts containers with seccomp enabled.",+ "scope": "deployment",+ "readonly": true+ },+ "max_memory": {+ "type": "string",+ "required": false,+ "label": "Max Memory",+ "default": "256m",+ "description": "Memory limit applied to each sandbox container. Common format: 256m or 1g.",+ "scope": "deployment",+ "readonly": true+ },+ "container_network": {+ "type": "string",+ "required": false,+ "label": "Container Network",+ "default": "none",+ "description": "Docker network attached to sandbox containers. Defaults to 'none' (no external network access); set to 'bridge' only if sandboxed code needs outbound network.",+ "scope": "deployment",+ "readonly": true+ },+ "sandbox_timeout": {+ "type": "string",+ "required": false,+ "label": "Sandbox Timeout",+ "default": "10s",+ "description": "Executor-manager container timeout for each sandbox run. Common format: 10s or 1m.",+ "scope": "deployment",+ "readonly": true+ }+ },+ "ssh": {+ "host": {+ "type": "string",+ "required": true,+ "label": "SSH Host",+ "placeholder": "192.168.1.10",+ "description": "Remote host that will execute generated code."+ },+ "port": {+ "type": "integer",+ "required": true,+ "label": "SSH Port",+ "default": 22,+ "min": 1,+ "max": 65535,+ "description": "SSH port on the remote host."+ },+ "username": {+ "type": "string",+ "required": true,+ "label": "SSH Username",+ "placeholder": "ragflow",+ "description": "Username used to connect to the remote host."+ },+ "password": {+ "type": "string",+ "required": false,+ "label": "SSH Password",+ "secret": true,+ "placeholder": "Optional when using a private key",+ "description": "Password-based SSH authentication."+ },+ "private_key": {+ "type": "string",+ "required": false,+ "label": "SSH Private Key",+ "secret": true,+ "multiline": true,+ "placeholder": "Paste PEM content or enter a local file path",+ "description": "Private key PEM content or a readable private key path on the RAGFlow host."+ },+ "passphrase": {+ "type": "string",+ "required": false,+ "label": "Private Key Passphrase",+ "secret": true,+ "placeholder": "Optional",+ "description": "Passphrase for the private key if it is encrypted."+ },+ "known_hosts": {+ "type": "string",+ "required": false,+ "label": "SSH known_hosts File",+ "placeholder": "/etc/ragflow/ssh_known_hosts",+ "description": "Path to an OpenSSH-format known_hosts file used to verify the remote host's key. When set, the file is loaded on top of the system host keys (~/.ssh/known_hosts). When unset, only system keys are used and unknown hosts are rejected."+ },+ "python_bin": {+ "type": "string",+ "required": false,+ "default": "python3",+ "label": "Python Binary",+ "description": "Python executable used for remote code execution."+ },+ "node_bin": {+ "type": "string",+ "required": false,+ "default": "node",+ "label": "Node.js Binary",+ "description": "Node.js executable used for remote JavaScript execution."+ },+ "work_dir": {+ "type": "string",+ "required": false,+ "label": "Remote Workspace Root",+ "default": "/tmp",+ "placeholder": "/tmp",+ "description": "Writable remote directory used to create a temporary workspace."+ },+ "timeout": {+ "type": "integer",+ "required": false,+ "label": "Timeout (seconds)",+ "default": 30,+ "min": 1,+ "max": 600,+ "description": "Maximum SSH execution time for a single run."+ },+ "max_output_bytes": {+ "type": "integer",+ "required": false,+ "label": "Max Output Bytes",+ "default": 1048576,+ "min": 1024,+ "max": 10485760,+ "description": "Maximum combined stdout and stderr size."+ },+ "max_artifacts": {+ "type": "integer",+ "required": false,+ "label": "Max Artifacts",+ "default": 20,+ "min": 0,+ "max": 100,+ "description": "Maximum number of files collected from the remote artifacts directory."+ },+ "max_artifact_bytes": {+ "type": "integer",+ "required": false,+ "label": "Max Artifact Bytes",+ "default": 10485760,+ "min": 1024,+ "max": 104857600,+ "description": "Maximum size of a single artifact file in bytes."+ }+ },+ "aliyun_codeinterpreter": {+ "access_key_id": {+ "type": "string",+ "required": true,+ "label": "Access Key ID",+ "placeholder": "LTAI5t...",+ "description": "Aliyun AccessKey ID for authentication",+ "secret": false+ },+ "access_key_secret": {+ "type": "string",+ "required": true,+ "label": "Access Key Secret",+ "placeholder": "••••••••••••••••",+ "description": "Aliyun AccessKey Secret for authentication",+ "secret": true+ },+ "account_id": {+ "type": "string",+ "required": true,+ "label": "Account ID",+ "placeholder": "1234567890...",+ "description": "Aliyun primary account ID, required for API calls"+ },+ "region": {+ "type": "string",+ "required": false,+ "label": "Region",+ "default": "cn-hangzhou",+ "description": "Aliyun region for Code Interpreter service",+ "options": [+ "cn-hangzhou",+ "cn-beijing",+ "cn-shanghai",+ "cn-shenzhen",+ "cn-guangzhou"+ ]+ },+ "template_name": {+ "type": "string",+ "required": false,+ "label": "Template Name",+ "placeholder": "my-interpreter",+ "description": "Optional sandbox template name for pre-configured environments"+ },+ "timeout": {+ "type": "integer",+ "required": false,+ "label": "Execution Timeout (seconds)",+ "default": 30,+ "min": 1,+ "max": 30,+ "description": "Code execution timeout (max 30 seconds - hard limit)"+ }+ },+ "e2b": {+ "api_key": {+ "type": "string",+ "required": true,+ "label": "API Key",+ "placeholder": "e2b_sk_...",+ "description": "E2B API key for authentication",+ "secret": true+ },+ "region": {+ "type": "string",+ "required": false,+ "label": "Region",+ "default": "us",+ "description": "E2B service region (us or eu)"+ },+ "timeout": {+ "type": "integer",+ "required": false,+ "label": "Request Timeout (seconds)",+ "default": 30,+ "min": 5,+ "max": 300,+ "description": "API request timeout for code execution"+ }+ },+ "tenki": {+ "api_key": {+ "type": "string",+ "required": true,+ "label": "API Key",+ "secret": true,+ "placeholder": "tk_...",+ "description": "Tenki API key. Create one at https://app.tenki.cloud under API Keys."+ },+ "base_url": {+ "type": "string",+ "required": false,+ "label": "API Endpoint",+ "placeholder": "https://api.tenki.cloud",+ "description": "Override the Tenki API endpoint. Leave empty for the default."+ },+ "image": {+ "type": "string",+ "required": false,+ "label": "Sandbox Image",+ "description": "Base image for sandboxes. Empty uses the Tenki default image (includes python3 and node)."+ },+ "allow_outbound": {+ "type": "boolean",+ "required": false,+ "label": "Allow Outbound Network",+ "default": false,+ "description": "Security-relevant. Disabled by default so sandboxed code has no network access. Enable it to let code make outbound connections (e.g. to install packages)."+ },+ "timeout": {+ "type": "integer",+ "required": false,+ "label": "Timeout (seconds)",+ "default": 30,+ "min": 1,+ "max": 600,+ "description": "Maximum execution time for a single run."+ },+ "max_lifetime": {+ "type": "integer",+ "required": false,+ "label": "Max Sandbox Lifetime (seconds)",+ "default": 3600,+ "min": 60,+ "max": 86400,+ "description": "Tenki reclaims a sandbox after this, guarding against leaks if the run is interrupted."+ },+ "cpu_cores": {+ "type": "integer",+ "required": false,+ "label": "vCPU Cores",+ "default": 0,+ "min": 0,+ "max": 16,+ "description": "vCPU per sandbox. 0 uses the Tenki default."+ },+ "memory_mb": {+ "type": "integer",+ "required": false,+ "label": "Memory (MB)",+ "default": 0,+ "min": 0,+ "max": 65536,+ "description": "Memory per sandbox in MB. 0 uses the Tenki default."+ },+ "disk_size_gb": {+ "type": "integer",+ "required": false,+ "label": "Disk Size (GB)",+ "default": 0,+ "min": 0,+ "max": 100,+ "description": "Disk size per sandbox in GB. 0 uses the Tenki default."+ },+ "max_output_bytes": {+ "type": "integer",+ "required": false,+ "label": "Max Output Bytes",+ "default": 1048576,+ "min": 1024,+ "max": 10485760,+ "description": "Maximum combined stdout and stderr size."+ },+ "max_artifacts": {+ "type": "integer",+ "required": false,+ "label": "Max Artifacts",+ "default": 20,+ "min": 0,+ "max": 100,+ "description": "Maximum number of files collected from the sandbox artifacts directory."+ },+ "max_artifact_bytes": {+ "type": "integer",+ "required": false,+ "label": "Max Artifact Bytes",+ "default": 10485760,+ "min": 1024,+ "max": 104857600,+ "description": "Maximum size of a single artifact file in bytes."+ }+ },+ "ucloud_agent_sandbox": {+ "api_key": {+ "type": "string",+ "required": true,+ "label": "API Key",+ "secret": true,+ "description": "UCloud Agent Sandbox API key."+ },+ "region": {+ "type": "string",+ "required": false,+ "label": "Region",+ "default": "cn-wlcb",+ "description": "UCloud Agent Sandbox region, for example cn-wlcb or us-ca."+ },+ "domain": {+ "type": "string",+ "required": false,+ "label": "Domain",+ "description": "Override the sandbox domain. Leave empty to derive it from Region."+ },+ "api_url": {+ "type": "string",+ "required": false,+ "label": "API URL",+ "description": "Override the UCloud Agent Sandbox control-plane API URL."+ },+ "template": {+ "type": "string",+ "required": false,+ "label": "Template",+ "default": "base",+ "description": "Sandbox template. The base template includes Python and Node.js."+ },+ "allow_internet_access": {+ "type": "boolean",+ "required": false,+ "label": "Allow Internet Access",+ "default": false,+ "description": "Allow sandboxed code to access the internet. Disabled by default."+ },+ "insecure_http": {+ "type": "boolean",+ "required": false,+ "label": "Use Insecure HTTP",+ "default": false,+ "description": "Use HTTP instead of HTTPS. Enable only for trusted private deployments."+ },+ "timeout": {+ "type": "integer",+ "required": false,+ "label": "Execution Timeout (seconds)",+ "default": 30,+ "min": 1,+ "max": 600+ },+ "sandbox_timeout": {+ "type": "integer",+ "required": false,+ "label": "Sandbox Lifetime (seconds)",+ "default": 300,+ "min": 60,+ "max": 86400+ },+ "max_output_bytes": {+ "type": "integer",+ "required": false,+ "label": "Max Output Bytes",+ "default": 1048576,+ "min": 1024,+ "max": 10485760+ },+ "max_artifacts": {+ "type": "integer",+ "required": false,+ "label": "Max Artifacts",+ "default": 20,+ "min": 0,+ "max": 100+ },+ "max_artifact_bytes": {+ "type": "integer",+ "required": false,+ "label": "Max Artifact Bytes",+ "default": 10485760,+ "min": 1024,+ "max": 104857600+ }+ }+ }+}diff --git a/internal/common/system_settings.go b/internal/common/system_settings.goindex d7ef609304..ba64b929a1 100644--- a/internal/common/system_settings.go+++ b/internal/common/system_settings.go@@ -65,6 +65,9 @@ func ValidateSystemSettingValue(setting entity.SystemSettings, value string) err}func InferSystemSettingDataType(name string) string {+ if name == "sandbox.provider_type" {+ return "string"+ }if strings.HasPrefix(name, "sandbox.") {return "json"}