Repository navigation
Feat: add local & ssh provider in admin panel - #15039
Conversation
📝 WalkthroughWalkthroughThis PR introduces SSH provider support for RAGFlow's sandboxed code execution system, alongside improvements to local and self-managed providers, a redesigned Admin UI for sandbox configuration, and supporting infrastructure updates including provider error handling, tool argument validation, and comprehensive tests. ChangesSandbox SSH Provider and Infrastructure
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
test/unit_test/agent/sandbox/test_local_provider.py (1)
1-7:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd a pytest priority marker for this test module.
This backend pytest file is missing a
p1/p2/p3marker, which makes prioritization inconsistent across the suite.Suggested fix
import pytest from agent.sandbox.providers.local import LocalProvider +pytestmark = pytest.mark.p2 + def _make_provider(tmp_path, **overrides):As per coding guidelines,
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python backend tests.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/agent/sandbox/test_local_provider.py` around lines 1 - 7, Add a module-level pytest priority marker (e.g., pytestmark = pytest.mark.p2) to this test file so the test runner can prioritize it consistently; locate the top of the module where imports (base64, sys, pytest, and LocalProvider) are declared and add the pytestmark assignment there referencing pytest (pytestmark = pytest.mark.<p1|p2|p3>) to satisfy the test/**/*.py priority marker policy.agent/sandbox/providers/self_managed.py (1)
386-393:⚠️ Potential issue | 🟠 Major | ⚡ Quick winURL validation regex is overly permissive and contains errors.
The regex pattern
r'^(https?://|http://localhost|http://[\d\.]+:[a-z]+:[/]|http://[\w\.]+:)'has issues:
[\d\.]+:[a-z]+:[/]doesn't match valid IPs (expects lowercase letters after port)- The pattern is fragmented and won't validate typical URLs like
http://sandbox-executor-manager:9385♻️ Suggested fix
- url_pattern = r'^(https?://|http://localhost|http://[\d\.]+:[a-z]+:[/]|http://[\w\.]+:)' + url_pattern = r'^https?://[\w\.\-]+(:\d+)?(/.*)?$' if not re.match(url_pattern, endpoint):🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/sandbox/providers/self_managed.py` around lines 386 - 393, The current URL validation using the url_pattern is incorrect and too permissive; replace the regex-based check for the local variable endpoint with a robust check using urllib.parse.urlparse (or a corrected regex) so that you verify the scheme is "http" or "https" and that netloc (host or IP, with optional port) is present; update the code that references url_pattern to instead parse endpoint and return False with the same error message if parsed.scheme not in ("http","https") or not parsed.netloc, ensuring values like "http://sandbox-executor-manager:9385" and valid IP:port forms pass and malformed strings fail.agent/sandbox/providers/local.py (1)
256-266:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winError messages reference removed environment variables.
The error messages still reference
SANDBOX_LOCAL_*environment variables, but the configuration now comes from the config dictionary. Update the messages to reflect the actual field names.♻️ Suggested fix
def _validate_limits(self) -> None: if self.timeout <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_TIMEOUT must be greater than 0.") + raise SandboxProviderConfigError("timeout must be greater than 0.") if self.max_memory_mb <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_MEMORY_MB must be greater than 0.") + raise SandboxProviderConfigError("max_memory_mb must be greater than 0.") if self.max_output_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_output_bytes must be greater than 0.") if self.max_artifacts < 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or equal to 0.") + raise SandboxProviderConfigError("max_artifacts must be >= 0.") if self.max_artifact_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_artifact_bytes must be greater than 0.")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/sandbox/providers/local.py` around lines 256 - 266, The _validate_limits method currently raises SandboxProviderConfigError with messages that refer to environment variables; update each error message to reference the actual configuration field names (timeout, max_memory_mb, max_output_bytes, max_artifacts, max_artifact_bytes) so they reflect the source of the value being validated; modify the raise calls inside _validate_limits to use clear messages like "<field> must be ..." referencing the field names and keep the same validation logic and exception type.rag/llm/chat_model.py (1)
296-297:⚠️ Potential issue | 🟠 Major | ⚡ Quick winBase._verbose_tool_use should stringify exceptions like LiteLLMBase does.
The
LiteLLMBase._verbose_tool_usewas updated (lines 1506-1510) to stringify exceptions before passing tojson.dumps, butBase._verbose_tool_usewas not. When tool execution fails, lines 411 and 524 call_verbose_tool_use(name, args, err if err else result), passing Exception objects whenerris not None. This causesjson.dumpsto raiseTypeError: Object of type Exception is not JSON serializable, which masks the actual tool error with a serialization error.🔧 Proposed fix to align with LiteLLMBase
def _verbose_tool_use(self, name, args, res): - return "<tool_call>" + json.dumps({"name": name, "args": args, "result": res}, ensure_ascii=False, indent=2) + "</tool_call>" + return "<tool_call>" + json.dumps( + {"name": name, "args": args, "result": str(res) if isinstance(res, Exception) else res}, + ensure_ascii=False, + indent=2, + ) + "</tool_call>"🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/llm/chat_model.py` around lines 296 - 297, Base._verbose_tool_use currently passes Exception objects into json.dumps causing TypeError when callers (the places that call _verbose_tool_use(name, args, err if err else result)) forward an exception; change Base._verbose_tool_use to stringify exceptions like LiteLLMBase._verbose_tool_use does (convert result to str(result) or repr(result) when it's an Exception or not JSON-serializable) before calling json.dumps so error objects are serializable and the original tool error is preserved.
🧹 Nitpick comments (1)
agent/sandbox/client.py (1)
181-181: 💤 Low valueSimplify class name fallback.
getattr(provider, "__class__", type(provider))is redundant since__class__is always present on Python objects.Suggested simplification
- provider_name = provider_manager.get_provider_name() or getattr(provider, "__class__", type(provider)).__name__ + provider_name = provider_manager.get_provider_name() or type(provider).__name__🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/sandbox/client.py` at line 181, The code computing provider_name uses a redundant getattr fallback; replace the expression provider_manager.get_provider_name() or getattr(provider, "__class__", type(provider)).__name__ with a simpler fallback that directly reads the provider's class name (e.g., provider_manager.get_provider_name() or provider.__class__.__name__ or provider_manager.get_provider_name() or type(provider).__name__), so update the assignment where provider_name is computed (referencing provider_manager.get_provider_name and the provider variable) to remove the unnecessary getattr call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@agent/sandbox/providers/ssh.py`:
- Around line 17-45: Add module-level logging by importing logging and creating
logger = logging.getLogger(__name__), then instrument the new SSH provider flow:
add logger.debug/info on successful and failed initialization in initialize(),
logger.info/debug when attempting and succeeding/ failing SSH connections in the
connection setup code, logger.debug/info before and after each command execution
(including command text and execution time) in execute_code(), logger.exception
or logger.error on caught exceptions in all error paths, and logger.info during
teardown/cleanup in destroy_instance(); reference the provider class and its
methods initialize(), execute_code(), and destroy_instance() when making these
changes.
In `@web/src/pages/admin/sandbox-settings.tsx`:
- Around line 591-592: Several UI strings in the Sandbox Settings JSX are
hardcoded; import and use useTranslation from react-i18next (const { t } =
useTranslation()) and replace raw text nodes with t('sandbox.runtimeSettings') /
t('sandbox.auth.title') / t('sandbox.auth.hint') / t('sandbox.auth.password') /
t('sandbox.auth.privateKey') / t('sandbox.auth.privateKeyHint') /
t('sandbox.execution.title') / t('sandbox.execution.hint') /
t('sandbox.deploymentDefaults.title') / t('sandbox.deploymentDefaults.hint') (or
similar keys) for the listed strings ("Runtime Settings", "Authentication" and
its hint, "Password", "Private Key", "Only required when the private key itself
is encrypted.", "Execution" and its hint, "Deployment Defaults" and its hint);
ensure you remove any use of project wrappers like useTranslate and update the
JSX headings and helper text elements to call t(...) instead, adding
corresponding i18n keys to the locale files.
---
Outside diff comments:
In `@agent/sandbox/providers/local.py`:
- Around line 256-266: The _validate_limits method currently raises
SandboxProviderConfigError with messages that refer to environment variables;
update each error message to reference the actual configuration field names
(timeout, max_memory_mb, max_output_bytes, max_artifacts, max_artifact_bytes) so
they reflect the source of the value being validated; modify the raise calls
inside _validate_limits to use clear messages like "<field> must be ..."
referencing the field names and keep the same validation logic and exception
type.
In `@agent/sandbox/providers/self_managed.py`:
- Around line 386-393: The current URL validation using the url_pattern is
incorrect and too permissive; replace the regex-based check for the local
variable endpoint with a robust check using urllib.parse.urlparse (or a
corrected regex) so that you verify the scheme is "http" or "https" and that
netloc (host or IP, with optional port) is present; update the code that
references url_pattern to instead parse endpoint and return False with the same
error message if parsed.scheme not in ("http","https") or not parsed.netloc,
ensuring values like "http://sandbox-executor-manager:9385" and valid IP:port
forms pass and malformed strings fail.
In `@rag/llm/chat_model.py`:
- Around line 296-297: Base._verbose_tool_use currently passes Exception objects
into json.dumps causing TypeError when callers (the places that call
_verbose_tool_use(name, args, err if err else result)) forward an exception;
change Base._verbose_tool_use to stringify exceptions like
LiteLLMBase._verbose_tool_use does (convert result to str(result) or
repr(result) when it's an Exception or not JSON-serializable) before calling
json.dumps so error objects are serializable and the original tool error is
preserved.
In `@test/unit_test/agent/sandbox/test_local_provider.py`:
- Around line 1-7: Add a module-level pytest priority marker (e.g., pytestmark =
pytest.mark.p2) to this test file so the test runner can prioritize it
consistently; locate the top of the module where imports (base64, sys, pytest,
and LocalProvider) are declared and add the pytestmark assignment there
referencing pytest (pytestmark = pytest.mark.<p1|p2|p3>) to satisfy the
test/**/*.py priority marker policy.
---
Nitpick comments:
In `@agent/sandbox/client.py`:
- Line 181: The code computing provider_name uses a redundant getattr fallback;
replace the expression provider_manager.get_provider_name() or getattr(provider,
"__class__", type(provider)).__name__ with a simpler fallback that directly
reads the provider's class name (e.g., provider_manager.get_provider_name() or
provider.__class__.__name__ or provider_manager.get_provider_name() or
type(provider).__name__), so update the assignment where provider_name is
computed (referencing provider_manager.get_provider_name and the provider
variable) to remove the unnecessary getattr call.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 220152f9-9aaf-41ab-8d19-518ed80fabde
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (18)
admin/server/services.pyagent/sandbox/client.pyagent/sandbox/providers/__init__.pyagent/sandbox/providers/local.pyagent/sandbox/providers/self_managed.pyagent/sandbox/providers/ssh.pyagent/tools/base.pyagent/tools/code_exec.pyconf/llm_factories.jsondocker/.envdocs/guides/agent/agent_quickstarts/sandbox_quickstart.mdpyproject.tomlrag/llm/chat_model.pytest/unit_test/agent/sandbox/test_local_provider.pytest/unit_test/agent/sandbox/test_sandbox_client.pytest/unit_test/agent/sandbox/test_ssh_provider.pyweb/src/pages/admin/sandbox-settings.tsxweb/src/services/admin.service.d.ts
💤 Files with no reviewable changes (1)
- conf/llm_factories.json
| from __future__ import annotations | ||
|
|
||
| import base64 | ||
| import io | ||
| import json | ||
| import mimetypes | ||
| import os | ||
| import posixpath | ||
| import shlex | ||
| import stat | ||
| import time | ||
| import uuid | ||
| from typing import TYPE_CHECKING, Any, Dict, List, Optional | ||
|
|
||
| from agent.sandbox.result_protocol import ( | ||
| build_javascript_wrapper, | ||
| build_python_wrapper, | ||
| extract_structured_result, | ||
| ) | ||
| from .base import ( | ||
| ExecutionResult, | ||
| SandboxInstance, | ||
| SandboxProvider, | ||
| SandboxProviderConfigError, | ||
| ) | ||
|
|
||
| if TYPE_CHECKING: | ||
| import paramiko | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Missing logging for new SSH provider flow.
This new provider implementation lacks any logging statements. Per coding guidelines, new flows should include logging for observability. Key points to log: initialization success/failure, connection attempts, command execution, errors, and cleanup operations.
Consider adding a logger at module level:
import logging
logger = logging.getLogger(__name__)Then add log statements in initialize(), execute_code(), destroy_instance(), and error paths.
As per coding guidelines: "Add logging for new flows" for **/*.py files.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/sandbox/providers/ssh.py` around lines 17 - 45, Add module-level
logging by importing logging and creating logger = logging.getLogger(__name__),
then instrument the new SSH provider flow: add logger.debug/info on successful
and failed initialization in initialize(), logger.info/debug when attempting and
succeeding/ failing SSH connections in the connection setup code,
logger.debug/info before and after each command execution (including command
text and execution time) in execute_code(), logger.exception or logger.error on
caught exceptions in all error paths, and logger.info during teardown/cleanup in
destroy_instance(); reference the provider class and its methods initialize(),
execute_code(), and destroy_instance() when making these changes.
| Runtime Settings | ||
| </h4> |
There was a problem hiding this comment.
Hardcoded UI strings should use t() for i18n.
The new SSH-specific UI sections contain several hardcoded English strings that bypass the existing i18n infrastructure. Wrap these in t() calls with appropriate translation keys:
- "Runtime Settings" (line 591)
- "Authentication" / "Choose one authentication method..." (lines 655-659)
- "Password" / "Private Key" (lines 676, 679)
- "Only required when the private key itself is encrypted." (lines 762-764)
- "Execution" / "Configure the remote workspace..." (lines 779-784)
- "Deployment Defaults" / "Read-only values loaded from..." (lines 874-879)
Example fix for one section
-<h4 className="text-sm font-medium text-text-primary">
- Runtime Settings
-</h4>
+<h4 className="text-sm font-medium text-text-primary">
+ {t('admin.sandboxSettingsPage.runtimeSettings')}
+</h4>As per coding guidelines: "Prefer useTranslation from react-i18next over project-wrapped utilities like useTranslate."
Also applies to: 651-661, 675-680, 761-764, 778-785, 873-880
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/admin/sandbox-settings.tsx` around lines 591 - 592, Several UI
strings in the Sandbox Settings JSX are hardcoded; import and use useTranslation
from react-i18next (const { t } = useTranslation()) and replace raw text nodes
with t('sandbox.runtimeSettings') / t('sandbox.auth.title') /
t('sandbox.auth.hint') / t('sandbox.auth.password') /
t('sandbox.auth.privateKey') / t('sandbox.auth.privateKeyHint') /
t('sandbox.execution.title') / t('sandbox.execution.hint') /
t('sandbox.deploymentDefaults.title') / t('sandbox.deploymentDefaults.hint') (or
similar keys) for the listed strings ("Runtime Settings", "Authentication" and
its hint, "Password", "Private Key", "Only required when the private key itself
is encrypted.", "Execution" and its hint, "Deployment Defaults" and its hint);
ensure you remove any use of project wrappers like useTranslate and update the
JSX headings and helper text elements to call t(...) instead, adding
corresponding i18n keys to the locale files.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15039 +/- ##
=======================================
Coverage 93.12% 93.12%
=======================================
Files 10 10
Lines 713 713
Branches 116 116
=======================================
Hits 664 664
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### Summary Adds a `tenki` sandbox provider that runs each agent code execution in a disposable Tenki (https://tenki.cloud) microVM (create → exec → destroy, no volumes or snapshots). Registration mirrors PR #15039, configure `api_key` and `project_id` in Admin > Sandbox Settings. Both runtimes are covered: - Python: `agent/sandbox/providers/tenki.py` (structured results + artifact collection). - Go: `internal/agent/sandbox/tenki.go`, mirroring the e2b provider and wired into the provider manager. `tenki-sandbox` is an optional dependency (it requires `protobuf>=6.31`, which differs from RAGFlow's pinned gRPC stack), lazily imported with a clear error when missing; installation is documented in the sandbox quickstart. Unit tests cover execution, structured results, artifacts (symlink/size/extension limits), non-zero exit, timeout, error mapping, and idempotent destroy. --------- Co-authored-by: yiming.wang <[email protected]>
### Summary Adds a `tenki` sandbox provider that runs each agent code execution in a disposable Tenki (https://tenki.cloud) microVM (create → exec → destroy, no volumes or snapshots). Registration mirrors PR infiniflow#15039, configure `api_key` and `project_id` in Admin > Sandbox Settings. Both runtimes are covered: - Python: `agent/sandbox/providers/tenki.py` (structured results + artifact collection). - Go: `internal/agent/sandbox/tenki.go`, mirroring the e2b provider and wired into the provider manager. `tenki-sandbox` is an optional dependency (it requires `protobuf>=6.31`, which differs from RAGFlow's pinned gRPC stack), lazily imported with a clear error when missing; installation is documented in the sandbox quickstart. Unit tests cover execution, structured results, artifacts (symlink/size/extension limits), non-zero exit, timeout, error mapping, and idempotent destroy. --------- Co-authored-by: yiming.wang <[email protected]>
What problem does this PR solve?
Feat: add local & ssh provider in admin panel
Type of change