Skip to content
Back to search

JoySafeter

๐Ÿš€ JoySafeter: An enterprise AI Agent Platformโ€”Not just chatting. buildingใ€runningใ€testing, and tracing autonomous Agent Teams with visual orchestration...

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/jd-opensource/JoySafeter with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/jd-opensource/JoySafeter'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/jd-opensource--joysafeter/badge.svg)](/listings/jd-opensource--joysafeter)

HTML

<a href="/listings/jd-opensource--joysafeter"><img src="/api/listings/jd-opensource--joysafeter/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

One-Click Launch (Recommended)

./deploy/quick-start.sh

The script provides an interactive menu to choose your startup mode and customize ports (with conflict detection):

| Mode | Description | Ports Configured | |------|-------------|-----------------| | **(1) Docker Compose Full Stack** | All services in containers, supports localhost or remote server IP/domain | Frontend, Backend, PostgreSQL, Redis | | **(2) Local Frontend Only** | `bun run dev`, supports connecting to remote backend | Frontend (can specify remote backend address) | | **(3) Local Backend Only** | `uvicorn --reload`, supports remote DB/Redis | Backend (can specify remote DB/Redis/frontend address) | | **(4) Local Frontend + Backend** | Auto-starts middleware, supports exposing via non-localhost address | Frontend, Backend |

All modes support remote deployment scenarios: - **Docker Compose Full Stack** โ€” choose deployment address (localhost or IP/domain) + http/https - **Local Frontend Only** โ€” optionally connect to a remote backend API (enter backend IP + port + protocol) - **Local Backend Only** โ€” optionally connect to remote PostgreSQL, Redis, and frontend (enter each address and port) - **Local Frontend + Backend** โ€” optionally expose services via a non-localhost address - Non-localhost deployments automatically update `frontend/.env` CSP whitelist (`NEXT_PUBLIC_CSP_CONNECT_SRC_EXTRA`)

./deploy/quick-start.sh --skip-env       # Skip .env file initialization
./deploy/quick-start.sh --skip-db-init   # Skip database initialization

Launch by Scenario

# โ”€โ”€โ”€ Development โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
./deploy/scripts/dev.sh                  # Docker full-stack dev (containerized frontend + backend)
./deploy/scripts/dev-local.sh            # Local dev prep (start middleware, run backend/frontend on host)
./deploy/scripts/dev-backend.sh          # Local backend only (requires middleware running)
./deploy/scripts/dev-frontend.sh         # Local frontend only (requires backend running)

# โ”€โ”€โ”€ Production โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
./deploy/scripts/prod.sh                 # Production deploy (pre-built images + docker-compose.prod.yml)
./deploy/scripts/prod.sh --skip-mcp      # Production without MCP service
./deploy/scripts/prod.sh --skip-pull     # Skip image pull, use local images

# โ”€โ”€โ”€ Middleware / Infrastructure โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
./deploy/scripts/start-middleware.sh     # Start middleware (PostgreSQL + Redis + MCP)
./deploy/scripts/minimal.sh             # Minimal startup (PostgreSQL + Redis only)
./deploy/scripts/minimal.sh --with-mcp  # Minimal + MCP service
./deploy/scripts/stop-middleware.sh      # Stop middleware

# โ”€โ”€โ”€ Test / CI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
./deploy/scripts/test.sh                 # Test environment (minimal deps, automation-friendly)

# โ”€โ”€โ”€ Install / Check โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
./deploy/install.sh                      # Interactive installation wizard (generates config files)
./deploy/install.sh --mode dev --non-interactive  # Non-interactive install
./deploy/scripts/check-env.sh           # Environment preflight (Docker, ports, config files)

# โ”€โ”€โ”€ Image Management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
./deploy/deploy.sh build                 # Build frontend + backend images
./deploy/deploy.sh build --all           # Build all images (including OpenClaw)
./deploy/deploy.sh push                  # Build and push to registry
./deploy/deploy.sh pull                  # Pull latest pre-built images

Default Ports

| Service | Port | URL | |---------|------|-----| | Frontend | `3000` | http://localhost:3000 | | Backend API | `8000` | http://localhost:8000 | | API Docs | `8000/docs` | Swagger UI | | PostgreSQL | `5432` | Database | | Redis | `6379` | Cache |

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md ยท README ยท 352 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <h1 align="center">
  2. <img src="docs/assets/joysafter.png" alt="JoySafeter" width="80" /><br/>
  3. JoySafeter
  4. </h1>
  5. <p align="center">
  6. <strong>The AI-native platform for building, orchestrating, and running security agents at scale.</strong><br/>
  7. <sub>From idea to production-grade security automation โ€” in minutes, not months.</sub>
  8. </p>
  9. <p align="center">
  10. <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License: Apache 2.0"></a>
  11. <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/Python-3.12+-3776AB?logo=python&logoColor=white" alt="Python 3.12+"></a>
  12. <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/Node.js-20+-339933?logo=nodedotjs&logoColor=white" alt="Node.js 20+"></a>
  13. <a href="https://github.com/langchain-ai/langgraph"><img src="https://img.shields.io/badge/LangGraph-1.0+-FF6F00?logo=chainlink&logoColor=white" alt="LangGraph"></a>
  14. <a href="https://fastapi.tiangolo.com/"><img src="https://img.shields.io/badge/FastAPI-0.122+-009688?logo=fastapi&logoColor=white" alt="FastAPI"></a>
  15. <a href="#"><img src="https://img.shields.io/badge/MCP-Protocol-purple" alt="MCP Protocol"></a>
  16. <a href="#"><img src="https://img.shields.io/badge/DeepAgents-v0.4-red" alt="DeepAgents v0.4"></a>
  17. </p>
  18. <p align="center">
  19. English | <a href="./README_CN.md">็ฎ€ไฝ“ไธญๆ–‡</a>
  20. </p>
  21. ---
  22. ## Why JoySafeter
  23. Traditional security tooling hits a ceiling: scripts are brittle, single agents lack context, and complex scenarios require 2โ€“3 engineers working in parallel. JoySafeter breaks that ceiling.
  24. | Challenge | Traditional Approach | JoySafeter |
  25. |-----------|---------------------|------------|
  26. | APK vulnerability analysis | Manual MobSF + engineer review | Autonomous agent: upload โ†’ analyze โ†’ report |
  27. | Penetration testing | Fixed scripts, static playbooks | Dynamic DeepAgents that adapt to findings in real time |
  28. | Tool integration | Custom glue code per tool | 200+ tools via MCP Protocol, zero glue |
  29. | Scale | Linear headcount growth | Agent teams that multiply capacity |
  30. > JoySafeter defines a new paradigm: **AI-driven Security Operations (AISecOps)** โ€” where multi-agent collaboration, cognitive memory, and scenario-matched skills replace manual coordination.
  31. ---
  32. ## Real-World Cases
  33. ### Case 1 โ€” APK Vulnerability Detection Agent
  34. > Upload an APK. Get an OWASP Mobile Top 10 report. No engineer required.
  35. <p align="center">
  36. <img src="docs/assets/APK-case.gif" alt="APK Vulnerability Detection Demo" width="800" />
  37. </p>
  38. **How it works:**
  39. 1. User uploads the APK file
  40. 2. Agent invokes MobSF for static analysis
  41. 3. Extracts critical risk signals โ€” permission abuse, hardcoded secrets, insecure network config
  42. 4. Deep-validates high-severity findings via Frida dynamic instrumentation
  43. 5. Auto-generates a structured report aligned to OWASP Mobile Top 10
  44. The entire flow โ€” from upload to report โ€” requires zero manual intervention, covering work that traditionally takes 2โ€“3 security engineers.
  45. ---
  46. ### Case 2 โ€” Penetration Testing Agent
  47. > Describe the target and scope. The agent plans, executes, and adapts โ€” then delivers a report.
  48. <p align="center">
  49. <img src="docs/assets/pentest-case.gif" alt="Penetration Testing Agent Demo" width="800" />
  50. </p>
  51. **How it works:**
  52. 1. Open the Workbench and create a new agent
  53. 2. Enable **DeepAgents mode** โ†’ select penetration testing skills
  54. 3. Provide an authorized target URL and test requirements
  55. 4. Agent runs autonomously โ€” if it discovers a login page, it automatically triggers auth bypass testing
  56. 5. Download the final report when the run completes
  57. > **Note:** Requires sandbox image `swr.cn-north-4.myhuaweicloud.com/ddn-k8s/ghcr.io/jd-opensource/joysafeter-sandbox:latest` configured in Sandbox Settings.
  58. This dynamic decision-making โ€” where the agent adapts its next step based on what it finds โ€” is what fixed scripts cannot replicate.
  59. ---
  60. ## Core Capabilities
  61. <table>
  62. <tr>
  63. <td width="50%">
  64. ### Visual Agent Builder
  65. - **No-code workflow editor** โ€” drag-and-drop nodes with loops, conditionals, and parallel execution
  66. - **Rapid Mode** โ€” describe in natural language, get a running agent team in minutes
  67. - **Deep Mode** โ€” visual debugging and step-by-step observability for complex security research
  68. </td>
  69. <td width="50%">
  70. ### 200+ Security Tools, Ready to Use
  71. - Pre-integrated **Nmap, Nuclei, Trivy**, and more
  72. - **MCP Protocol** โ€” extend with any tool via Model Context Protocol
  73. - **30+ pre-built skills** โ€” penetration testing, document analysis, cloud security, and more
  74. </td>
  75. </tr>
  76. <tr>
  77. <td width="50%">
  78. ### DeepAgents Orchestration
  79. - **Manager-Worker multi-level** agent collaboration
  80. - **Memory evolution** โ€” long/short-term memory for continuous learning across sessions
  81. - **Skill system** โ€” versioned, reusable capability units with progressive disclosure
  82. - **LangGraph engine** โ€” graph-based workflows with full state management
  83. </td>
  84. <td width="50%">
  85. ### Enterprise Ready
  86. - **Multi-tenancy** โ€” isolated workspaces with role-based access control
  87. - **Full audit trail** โ€” execution tracing and compliance governance
  88. - **SSO integration** โ€” GitHub, Google, Microsoft, OIDC (Keycloak, Authentik, GitLab), JD SSO
  89. - **Multi-tenant sandbox** โ€” per-user isolated code execution, zero state leakage
  90. </td>
  91. </tr>
  92. </table>
  93. ---
  94. ## Quick Start
  95. ### One-Click Launch (Recommended)
  96. ```bash
  97. ./deploy/quick-start.sh
  98. ```
  99. The script provides an interactive menu to choose your startup mode and customize ports (with conflict detection):
  100. | Mode | Description | Ports Configured |
  101. |------|-------------|-----------------|
  102. | **(1) Docker Compose Full Stack** | All services in containers, supports localhost or remote server IP/domain | Frontend, Backend, PostgreSQL, Redis |
  103. | **(2) Local Frontend Only** | `bun run dev`, supports connecting to remote backend | Frontend (can specify remote backend address) |
  104. | **(3) Local Backend Only** | `uvicorn --reload`, supports remote DB/Redis | Backend (can specify remote DB/Redis/frontend address) |
  105. | **(4) Local Frontend + Backend** | Auto-starts middleware, supports exposing via non-localhost address | Frontend, Backend |
  106. All modes support remote deployment scenarios:
  107. - **Docker Compose Full Stack** โ€” choose deployment address (localhost or IP/domain) + http/https
  108. - **Local Frontend Only** โ€” optionally connect to a remote backend API (enter backend IP + port + protocol)
  109. - **Local Backend Only** โ€” optionally connect to remote PostgreSQL, Redis, and frontend (enter each address and port)
  110. - **Local Frontend + Backend** โ€” optionally expose services via a non-localhost address
  111. - Non-localhost deployments automatically update `frontend/.env` CSP whitelist (`NEXT_PUBLIC_CSP_CONNECT_SRC_EXTRA`)
  112. ```bash
  113. ./deploy/quick-start.sh --skip-env # Skip .env file initialization
  114. ./deploy/quick-start.sh --skip-db-init # Skip database initialization
  115. ```
  116. ### Launch by Scenario
  117. ```bash
  118. # โ”€โ”€โ”€ Development โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  119. ./deploy/scripts/dev.sh # Docker full-stack dev (containerized frontend + backend)
  120. ./deploy/scripts/dev-local.sh # Local dev prep (start middleware, run backend/frontend on host)
  121. ./deploy/scripts/dev-backend.sh # Local backend only (requires middleware running)
  122. ./deploy/scripts/dev-frontend.sh # Local frontend only (requires backend running)
  123. # โ”€โ”€โ”€ Production โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  124. ./deploy/scripts/prod.sh # Production deploy (pre-built images + docker-compose.prod.yml)
  125. ./deploy/scripts/prod.sh --skip-mcp # Production without MCP service
  126. ./deploy/scripts/prod.sh --skip-pull # Skip image pull, use local images
  127. # โ”€โ”€โ”€ Middleware / Infrastructure โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  128. ./deploy/scripts/start-middleware.sh # Start middleware (PostgreSQL + Redis + MCP)
  129. ./deploy/scripts/minimal.sh # Minimal startup (PostgreSQL + Redis only)
  130. ./deploy/scripts/minimal.sh --with-mcp # Minimal + MCP service
  131. ./deploy/scripts/stop-middleware.sh # Stop middleware
  132. # โ”€โ”€โ”€ Test / CI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  133. ./deploy/scripts/test.sh # Test environment (minimal deps, automation-friendly)
  134. # โ”€โ”€โ”€ Install / Check โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  135. ./deploy/install.sh # Interactive installation wizard (generates config files)
  136. ./deploy/install.sh --mode dev --non-interactive # Non-interactive install
  137. ./deploy/scripts/check-env.sh # Environment preflight (Docker, ports, config files)
  138. # โ”€โ”€โ”€ Image Management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
  139. ./deploy/deploy.sh build # Build frontend + backend images
  140. ./deploy/deploy.sh build --all # Build all images (including OpenClaw)
  141. ./deploy/deploy.sh push # Build and push to registry
  142. ./deploy/deploy.sh pull # Pull latest pre-built images
  143. ```
  144. ### Default Ports
  145. | Service | Port | URL |
  146. |---------|------|-----|
  147. | Frontend | `3000` | http://localhost:3000 |
  148. | Backend API | `8000` | http://localhost:8000 |
  149. | API Docs | `8000/docs` | Swagger UI |
  150. | PostgreSQL | `5432` | Database |
  151. | Redis | `6379` | Cache |
  152. > **Prerequisites:** Docker + Docker Compose. See [INSTALL.md](INSTALL.md) for detailed installation guide, [deploy/PRODUCTION_IP_GUIDE.md](deploy/PRODUCTION_IP_GUIDE.md) for production deployment.
  153. ---
  154. ## Architecture
  155. <p align="center">
  156. <img src="docs/architecture-diagram.png" alt="JoySafeter System Architecture" width="900" />
  157. </p>
  158. > Full architecture details: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
  159. **Key design principles:**
  160. - **Graph-based execution** โ€” every agent workflow is a stateful LangGraph, enabling pause, resume, and branch
  161. - **Unified Run Center** โ€” Chat, Copilot, and Skill Creator share a single event-sourced run lifecycle (Run โ†’ Event โ†’ Snapshot)
  162. - **Unified WebSocket layer** โ€” BaseWsClient abstract class; Chat / Run / Notification clients share lifecycle, auth (ws-token), and reconnect logic
  163. - **Full-chain trace_id propagation** โ€” contextvars-based request tracing from HTTP/WS entry through LangGraph to persistence
  164. - **Glass-box observability** โ€” real-time Langfuse tracing of every agent decision and state transition
  165. - **RAII sandbox isolation** โ€” per-user Docker containers with automatic handle release, zero state leakage
  166. - **Canonical model identifiers** โ€” full-stack (provider_name, model_name) resolution via ModelService โ†’ ModelFactory
  167. - **Layered skill system** โ€” skills are versioned units that compose into workflows without coupling
  168. ### User Journey โ€” Quick Start in 9 Steps
  169. <p align="center">
  170. <img src="docs/user-journey-quickstart.png" alt="JoySafeter Quick Start User Journey" width="900" />
  171. </p>
  172. > **Login** โ†’ **Configure Models** โ†’ **MCP Tools** โ†’ **Skill Management** โ†’ **Build Agent** โ†’ **Self-Test (Langfuse Trace)** โ†’ **Publish** โ†’ **Chat UI** โ†’ **Run Center**
  173. ---
  174. ## Tech Stack
  175. | Layer | Technology | Purpose |
  176. |-------|------------|---------|
  177. | **Frontend** | Next.js 16, React 19, TypeScript | Server-side rendering, App Router |
  178. | **UI** | Radix UI, Tailwind CSS, Framer Motion | Accessible, animated components |
  179. | **State** | Zustand, TanStack Query | Client & server state |
  180. | **Workflow Editor** | React Flow | Interactive node-based builder |
  181. | **Backend** | FastAPI, Python 3.12+ | Async API with OpenAPI docs |
  182. | **AI Framework** | LangChain, LangGraph, DeepAgents | Agent orchestration & workflows |
  183. | **MCP** | mcp 1.20+, fastmcp 2.14+ | Tool protocol support |
  184. | **Database** | PostgreSQL, SQLAlchemy 2.0 | Async ORM with migrations |
  185. | **Cache** | Redis | Session cache & rate limiting |
  186. | **Observability** | Langfuse, Loguru | Tracing & structured logging |
  187. ---
  188. ## What's New
  189. > Full history: [CHANGELOG.md](CHANGELOG.md)
  190. | Tag | Feature | What it means |
  191. |-----|---------|---------------|
  192. | **NEW** | **Run Center Architecture** | Chat & Copilot fully integrated into Run Center โ€” run details, session recovery, and live event replay on page refresh |
  193. | **NEW** | **Dark Mode & Preferences** | System / Light / Dark theme switching; redesigned profile page with language & theme preferences |
  194. | **NEW** | **Unified WebSocket Layer** | BaseWsClient abstract class โ€” Chat, Run, and Notification clients share lifecycle, auth (ws-token), and reconnect logic |
  195. | **NEW** | **Full-Chain trace_id Propagation** | End-to-end request tracing via contextvars for complete observability |
  196. | **NEW** | **Ollama One-Click Integration** | Local Ollama model provider added out of the box |
  197. | **NEW** | **Version Display** | In-app version info tied to bump-version.sh release pipeline |
  198. | **NEW** | **Unified Model Identifiers** | Full-stack (provider_name, model_name) canonical form with data migration โ€” no more legacy field ambiguity |
  199. | **UPGRADE** | **Design Token Overhaul** | Hardcoded colors, font sizes, and border radii replaced with CSS variables and Tailwind tokens; z-index and typography scales unified |
  200. | **UPGRADE** | **Sandbox Overhaul** | RAII handle management, adapter API uploads, security hardening |
  201. | **UPGRADE** | **Frontend Component Extraction** | ConfirmDialog, UnifiedDialog, InlineRenameInput, SidebarContextMenu, AgentListContext โ€” less prop drilling, more reuse |
  202. | **UPGRADE** | **i18n & Code Quality** | Backend error messages internationalized; email templates moved to Jinja2; LLM prompts externalized to Markdown; 129 unused SVG icons removed |
  203. ---
  204. ## Documentation
  205. ### Getting Started
  206. - [INSTALL.md](INSTALL.md) โ€” Installation guide (Docker / manual / pre-built images)
  207. - [DEVELOPMENT.md](DEVELOPMENT.md) โ€” Local development setup
  208. - [deploy/README.md](deploy/README.md) โ€” Docker deployment
  209. - [deploy/PRODUCTION_IP_GUIDE.md](deploy/PRODUCTION_IP_GUIDE.md) โ€” Production deployment
  210. ### Deep Dive
  211. - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) โ€” Architecture overview
  212. - [backend/README.md](backend/README.md) โ€” Backend guide
  213. - [frontend/README.md](frontend/README.md) โ€” Frontend guide
  214. ### Tutorials
  215. See [docs/tutorials/](docs/tutorials/) for step-by-step guides on model setup, MCP integration, skill development, and more.
  216. ### Governance
  217. - [CONTRIBUTING.md](CONTRIBUTING.md) โ€” Contributing guide
  218. - [SECURITY.md](SECURITY.md) โ€” Security policy
  219. - [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) โ€” Code of conduct
  220. ---
  221. ## Community
  222. Join the WeChat user group for questions and discussion:
  223. <p align="center">
  224. <img src="docs/assets/wechat-group-3.png" alt="JoySafeter User Group 3" width="280" />
  225. &nbsp;&nbsp;&nbsp;&nbsp;
  226. <img src="docs/assets/wechat-group-4.png" alt="JoySafeter User Group 4" width="280" />
  227. </p>
  228. ---
  229. ## Contributing
  230. ```bash
  231. git clone https://github.com/jd-opensource/JoySafeter.git
  232. git checkout -b feature/amazing-feature
  233. git commit -m 'feat: add amazing feature'
  234. git push origin feature/amazing-feature
  235. ```
  236. See [CONTRIBUTING.md](CONTRIBUTING.md) for full guidelines.
  237. ---
  238. ## License
  239. Apache License 2.0 โ€” see [LICENSE](LICENSE) for details.
  240. Third-party component licenses: [THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md)
  241. ---
  242. ## Acknowledgments
  243. <table>
  244. <tr>
  245. <td align="center"><a href="https://github.com/langchain-ai/langchain"><img src="https://avatars.githubusercontent.com/u/126733545?s=64" width="48"/><br/><sub>LangChain</sub></a></td>
  246. <td align="center"><a href="https://github.com/langchain-ai/langgraph"><img src="https://avatars.githubusercontent.com/u/126733545?s=64" width="48"/><br/><sub>LangGraph</sub></a></td>
  247. <td align="center"><a href="https://fastapi.tiangolo.com/"><img src="https://fastapi.tiangolo.com/img/icon-white.svg" width="48"/><br/><sub>FastAPI</sub></a></td>
  248. <td align="center"><a href="https://nextjs.org/"><img src="https://assets.vercel.com/image/upload/v1662130559/nextjs/Icon_dark_background.png" width="48"/><br/><sub>Next.js</sub></a></td>
  249. <td align="center"><a href="https://www.radix-ui.com/"><img src="https://avatars.githubusercontent.com/u/75042455?s=64" width="48"/><br/><sub>Radix UI</sub></a></td>
  250. </tr>
  251. </table>
  252. ---
  253. <p align="center">
  254. <sub>Made with โค๏ธ by the JoySafeter Team</sub><br/>
  255. <sub>For commercial solutions, contact JD Technology Solutions Team at <a href="mailto:org.ospo1@jd.com">org.ospo1@jd.com</a></sub>
  256. </p>
backend/app/core/agent/backends/pydantic_adapter.py ยท Bundled script ยท 1,028 lines ยท 2 findings marked
  1. """Adapter for pydantic-ai-backend DockerSandbox to SandboxBackendProtocol.
  2. This module provides an adapter layer that bridges pydantic-ai-backend's
  3. DockerSandbox implementation with deepAgents' SandboxBackendProtocol interface.
  4. Supports advanced features from pydantic-ai-backend 0.1.5+:
  5. - RuntimeConfig for pre-configured environments (python-datascience, python-web, etc.)
  6. - session_id for multi-user session management
  7. - idle_timeout for automatic container cleanup
  8. - volumes for Docker volume mounting
  9. """
  10. import uuid
  11. from datetime import datetime
  12. from pathlib import Path
  13. from typing import List
  14. from deepagents.backends.protocol import (
  15. EditResult,
  16. ExecuteResponse,
  17. FileDownloadResponse,
  18. FileInfo,
  19. FileUploadResponse,
  20. GrepMatch,
  21. SandboxBackendProtocol,
  22. WriteResult,
  23. )
  24. from deepagents.backends.utils import format_read_response
  25. from loguru import logger
  26. from pydantic_ai_backends import DockerSandbox
  27. from app.core.agent.backends.constants import (
  28. DEFAULT_AUTO_REMOVE,
  29. DEFAULT_COMMAND_TIMEOUT,
  30. DEFAULT_DOCKER_IMAGE,
  31. DEFAULT_IDLE_TIMEOUT,
  32. DEFAULT_MAX_OUTPUT_SIZE,
  33. DEFAULT_WORKING_DIR,
  34. )
  35. from app.core.agent.backends.runtime_config import (
  36. BUILTIN_RUNTIMES,
  37. RuntimeConfig,
  38. get_builtin_runtime,
  39. list_builtin_runtimes,
  40. resolve_runtime,
  41. )
  42. from app.utils.backend_utils import create_execute_response
  43. # Re-export for backward compatibility
  44. __all__ = [
  45. "PydanticSandboxAdapter",
  46. "RuntimeConfig",
  47. "BUILTIN_RUNTIMES",
  48. "get_builtin_runtime",
  49. "list_builtin_runtimes",
  50. ]
  51. class PydanticSandboxAdapter(SandboxBackendProtocol):
  52. """Adapter that wraps pydantic-ai-backend's DockerSandbox for deepAgents.
  53. This adapter implements SandboxBackendProtocol by delegating to
  54. pydantic-ai-backend's DockerSandbox, providing a seamless integration
  55. with deepAgents' FilesystemMiddleware.
  56. **Lifecycle Management:**
  57. - `start()` is called automatically in `__init__` to start the container
  58. - `stop()`: stop the container only (no remove); use for stop/restart semantics
  59. - `cleanup()`: stop and remove the container; use for rebuild/teardown only
  60. - With auto_remove=False, stop() keeps the container so start() can restart it
  61. **Features:**
  62. - Full SandboxBackendProtocol compatibility
  63. - Delegates to pydantic-ai-backend's DockerSandbox
  64. - Explicit lifecycle management (start/stop)
  65. - Automatic resource cleanup
  66. - Error handling and logging
  67. - Idempotent start/stop operations
  68. - RuntimeConfig support for pre-configured environments
  69. - Session management with session_id
  70. - Idle timeout for automatic container cleanup
  71. - Docker volume mounting support
  72. **Pre-configured Runtimes:**
  73. - python-minimal: Basic Python 3.12 environment
  74. - python-datascience: Pandas, NumPy, Matplotlib, Scikit-learn
  75. - python-web: FastAPI, Uvicorn, SQLAlchemy, httpx
  76. - python-ml: PyTorch, Transformers
  77. - node-minimal: Basic Node.js 20 environment
  78. - node-react: TypeScript, Vite, React
  79. Example:
  80. ```python
  81. from app.core.agent.backends.pydantic_adapter import (
  82. PydanticSandboxAdapter,
  83. RuntimeConfig,
  84. )
  85. # Basic usage
  86. adapter = PydanticSandboxAdapter(image="python:3.12-slim")
  87. # Using pre-configured runtime
  88. adapter = PydanticSandboxAdapter(runtime="python-datascience")
  89. # Using custom runtime
  90. custom_runtime = RuntimeConfig(
  91. name="ml-env",
  92. base_image="python:3.12-slim",
  93. packages=["torch", "transformers"],
  94. )
  95. adapter = PydanticSandboxAdapter(runtime=custom_runtime)
  96. # With session management and volume mounting
  97. adapter = PydanticSandboxAdapter(
  98. runtime="python-web",
  99. session_id="user-123",
  100. idle_timeout=1800,
  101. volumes={"/data": "/app/shared"},
  102. )
  103. # Use as context manager
  104. with PydanticSandboxAdapter(runtime="python-minimal") as adapter:
  105. result = adapter.execute("python --version")
  106. ```
  107. """
  108. def __init__(
  109. self,
  110. image: str = DEFAULT_DOCKER_IMAGE,
  111. working_dir: str = DEFAULT_WORKING_DIR,
  112. auto_remove: bool = DEFAULT_AUTO_REMOVE,
  113. max_output_size: int = DEFAULT_MAX_OUTPUT_SIZE,
  114. command_timeout: int = DEFAULT_COMMAND_TIMEOUT,
  115. runtime: RuntimeConfig | str | None = None,
  116. session_id: str | None = None,
  117. idle_timeout: int = DEFAULT_IDLE_TIMEOUT,
  118. volumes: dict[str, str] | None = None,
  119. ):
  120. """Initialize PydanticSandboxAdapter.
  121. Creates and starts the Docker sandbox container following the
  122. pydantic-ai-backend lifecycle pattern. The container is automatically
  123. started via `start()` method.
  124. Args:
  125. image: Docker image to use (default: python:3.12-slim).
  126. Ignored if runtime is specified.
  127. working_dir: Working directory in container
  128. auto_remove: Auto-remove container on exit
  129. max_output_size: Maximum command output size in characters
  130. command_timeout: Command execution timeout in seconds
  131. runtime: Pre-configured runtime environment. Can be:
  132. - str: Name of builtin runtime ("python-datascience", "python-web", etc.)
  133. - RuntimeConfig: Custom runtime configuration
  134. - None: Use image parameter directly
  135. session_id: Session identifier for multi-user scenarios.
  136. Used to track and potentially reuse sandbox instances.
  137. idle_timeout: Time in seconds before idle container is cleaned up (default: 3600)
  138. volumes: Docker volume mappings {host_path: container_path}
  139. Raises:
  140. ImportError: If pydantic-ai-backend is not installed
  141. RuntimeError: If DockerSandbox creation fails
  142. Note:
  143. The sandbox container is automatically started during initialization.
  144. Call `cleanup()` when done to stop and remove the container.
  145. Example:
  146. ```python
  147. # Using builtin runtime
  148. adapter = PydanticSandboxAdapter(runtime="python-datascience")
  149. # Using custom runtime
  150. adapter = PydanticSandboxAdapter(
  151. runtime=RuntimeConfig(
  152. name="custom",
  153. base_image="python:3.11",
  154. packages=["requests"],
  155. ),
  156. )
  157. # With volumes
  158. adapter = PydanticSandboxAdapter(
  159. runtime="python-web",
  160. volumes={"/host/data": "/container/data"},
  161. )
  162. ```
  163. """
  164. # Store parameters
  165. self.runtime = runtime
  166. self.session_id = session_id
  167. self.idle_timeout = idle_timeout
  168. self.volumes = volumes or {}
  169. # Resolve runtime to get effective image and config
  170. effective_image, self._runtime_config = resolve_runtime(image, runtime)
  171. self._id = session_id or str(uuid.uuid4())
  172. self.image = effective_image
  173. self.working_dir = working_dir
  174. self.auto_remove = auto_remove
  175. self.max_output_size = max_output_size
  176. self.command_timeout = command_timeout
  177. self._started = False # Track sandbox start state
  178. self._saved_container_id: str | None = None # For restart: reuse same container after stop
  179. # Log initialization
  180. runtime_info = f", runtime={self._runtime_config.name}" if self._runtime_config else ""
  181. volumes_info = f", volumes={len(self.volumes)}" if self.volumes else ""
  182. logger.info(
  183. f"Initializing PydanticSandboxAdapter: id={self._id}, "
  184. f"image={self.image}, working_dir={working_dir}{runtime_info}{volumes_info}"
  185. )
  186. # Prepare runtime parameter for pydantic-ai-backend
  187. pydantic_runtime = None
  188. if self._runtime_config:
  189. pydantic_runtime = self._runtime_config.to_pydantic_runtime()
  190. # Create DockerSandbox with pydantic-ai-backend API
  191. try:
  192. sandbox_kwargs: dict = {
  193. "image": self.image,
  194. "work_dir": working_dir,
  195. "auto_remove": auto_remove,
  196. "runtime": pydantic_runtime,
  197. "session_id": self.session_id,
  198. "idle_timeout": self.idle_timeout,
  199. "volumes": self.volumes if self.volumes else None,
  200. }
  201. self._sandbox = DockerSandbox(**sandbox_kwargs)
  202. logger.info(f"DockerSandbox created: id={self._id}, image={self.image}")
  203. except Exception as e:
  204. logger.error(f"Failed to create DockerSandbox for adapter {self._id}: {e}", exc_info=True)
  205. raise RuntimeError(f"Failed to create DockerSandbox: {e}") from e
  206. # Start the sandbox
  207. logger.debug(f"Starting sandbox {self._id}...")
  208. self.start()
  209. @property
  210. def id(self) -> str:
  211. """Unique identifier for this backend instance."""
  212. return self._id
  213. def is_started(self) -> bool:
  214. """Check if the sandbox container is started.
  215. Returns:
  216. True if the sandbox is started, False otherwise.
  217. """
  218. return self._started
  219. def get_runtime_config(self) -> RuntimeConfig | None:
  220. """Get the current runtime configuration.
  221. Returns:
  222. RuntimeConfig instance, or None if no runtime config is in use.
  223. """
  224. return self._runtime_config
  225. def get_container_id(self) -> str | None:
  226. """Get the Docker container ID for persistence/reconnection.
  227. Returns:
  228. Docker container ID string, or None if not available.
  229. """
  230. container = getattr(self._sandbox, "_container", None)
  231. if container is not None:
  232. return getattr(container, "id", None)
  233. return self._saved_container_id
  234. @classmethod
  235. def from_existing_container(
  236. cls,
  237. container,
  238. session_id: str,
  239. image: str = DEFAULT_DOCKER_IMAGE,
  240. idle_timeout: int = DEFAULT_IDLE_TIMEOUT,
  241. working_dir: str = DEFAULT_WORKING_DIR,
  242. max_output_size: int = DEFAULT_MAX_OUTPUT_SIZE,
  243. command_timeout: int = DEFAULT_COMMAND_TIMEOUT,
  244. ) -> "PydanticSandboxAdapter":
  245. """Create an adapter that wraps an already-running Docker container.
  246. Used for app-restart recovery: reconnect to a container that was
  247. created in a previous process lifetime.
  248. Args:
  249. container: A docker.models.containers.Container instance (already running).
  250. session_id: Session/sandbox ID.
  251. image: Image name (for metadata only).
  252. idle_timeout: Idle timeout in seconds.
  253. working_dir: Working directory inside the container.
  254. max_output_size: Max command output size.
  255. command_timeout: Command timeout in seconds.
  256. Returns:
  257. PydanticSandboxAdapter wrapping the existing container.
  258. """
  259. # Create a minimal DockerSandbox and inject the container
  260. sandbox = DockerSandbox(
  261. image=image,
  262. work_dir=working_dir,
  263. auto_remove=False,
  264. session_id=session_id,
  265. idle_timeout=idle_timeout,
  266. )
  267. # Inject the existing container so DockerSandbox uses it
  268. sandbox._container = container
  269. # Build adapter without calling __init__ (which would start a new container)
  270. adapter = cls.__new__(cls)
  271. adapter.runtime = None
  272. adapter.session_id = session_id
  273. adapter.idle_timeout = idle_timeout
  274. adapter.volumes = {}
  275. adapter._runtime_config = None
  276. adapter._id = session_id
  277. adapter.image = image
  278. adapter.working_dir = working_dir
  279. adapter.auto_remove = False
  280. adapter.max_output_size = max_output_size
  281. adapter.command_timeout = command_timeout
  282. adapter._started = True
  283. adapter._saved_container_id = None
  284. adapter._sandbox = sandbox
  285. logger.info(
  286. f"PydanticSandboxAdapter.from_existing_container: "
  287. f"id={session_id}, container={getattr(container, 'short_id', 'unknown')}"
  288. )
  289. return adapter
  290. def start(self) -> None:
  291. """Start the Docker sandbox container. Idempotent. Restart reuses same container if available."""
  292. if self._started:
  293. return
  294. upstream_container = getattr(self._sandbox, "_container", None)
  295. if self._saved_container_id and upstream_container is None:
  296. try:
  297. from app.core.agent.backends.docker_check import get_docker_client
  298. client = get_docker_client()
  299. container = client.containers.get(self._saved_container_id)
  300. container.start()
  301. self._sandbox._container = container
  302. self._started = True
  303. self._saved_container_id = None
  304. logger.info(f"Sandbox {self._id} restarted (same container)")
  305. return
  306. except Exception as e:
  307. logger.warning(f"Failed to restart existing container {self._id}, will create new: {e}")
  308. stale_id = self._saved_container_id
  309. self._saved_container_id = None
  310. if stale_id is not None:
  311. self._force_remove_container(stale_id)
  312. try:
  313. if hasattr(self._sandbox, "start"):
  314. self._sandbox.start()
  315. self._started = True
  316. logger.info(f"Sandbox {self._id} started (image={self.image})")
  317. except Exception as e:
  318. logger.error(f"Failed to start sandbox {self._id}: {e}")
  319. raise RuntimeError(f"Failed to start sandbox {self._id}: {e}") from e
  320. # Dangerous command patterns (defense-in-depth, not sole security boundary)
  321. _DANGEROUS_PATTERNS = [
  322. r"rm\s+-rf\s+/\s*$", # rm -rf /
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 373 on GitHub
  323. r"mkfs\.", # format disk
  324. r"dd\s+.*of=/dev/", # write to device
  325. r":\(\)\s*\{", # fork bomb :(){ :|:& };:
  326. ]
  327. _DANGEROUS_RE = None # Lazy-compiled combined regex
  328. @classmethod
  329. def _get_dangerous_re(cls):
  330. if cls._DANGEROUS_RE is None:
  331. import re
  332. cls._DANGEROUS_RE = re.compile("|".join(f"(?:{p})" for p in cls._DANGEROUS_PATTERNS))
  333. return cls._DANGEROUS_RE
  334. def _exec_command(self, command: str) -> tuple[str, int]:
  335. """Execute command in sandbox with safety checks.
  336. Args:
  337. command: Shell command to execute
  338. Returns:
  339. Tuple of (output, exit_code)
  340. """
  341. if self._get_dangerous_re().search(command):
  342. logger.warning(f"[{self._id}] Blocked dangerous command: {command[:100]}")
  343. return "Error: command blocked by security policy", 1
  344. logger.debug(f"[{self._id}] _exec_command START: {command[:100]}")
  345. try:
  346. result = self._sandbox.execute(command)
  347. # 1. Handle ExecuteResponse from pydantic-ai-backend (output/exit_code/truncated)
  348. # This is the primary format returned by DockerSandbox.execute()
  349. if hasattr(result, "output") and hasattr(result, "exit_code"):
  350. output = result.output if isinstance(result.output, str) else str(result.output or "")
  351. exit_code = result.exit_code
  352. logger.debug(f"[{self._id}] _exec_command END: exit_code={exit_code}, output_len={len(output)}")
  353. return output, exit_code
  354. # 2. Handle ExecutionResult format (stdout/returncode)
  355. if hasattr(result, "stdout") and hasattr(result, "returncode"):
  356. output = (
  357. result.stdout.decode("utf-8", errors="replace")
  358. if isinstance(result.stdout, bytes)
  359. else str(result.stdout or "")
  360. )
  361. logger.debug(
  362. f"[{self._id}] _exec_command END (ExecutionResult): exit_code={result.returncode}, output_len={len(output)}"
  363. )
  364. return output, result.returncode
  365. # 3. Handle dict format (TypedDict or plain dict) - supports both naming conventions
  366. if isinstance(result, dict):
  367. output = str(result.get("output", result.get("stdout", "")))
  368. exit_code_raw = result.get("exit_code", result.get("returncode", 0))
  369. exit_code = 0
  370. if exit_code_raw is not None:
  371. try:
  372. exit_code = int(exit_code_raw)
  373. except (TypeError, ValueError):
  374. exit_code = 0
  375. logger.debug(f"[{self._id}] _exec_command END (dict): exit_code={exit_code}, output_len={len(output)}")
  376. return output, exit_code
  377. # 4. Fallback - should rarely happen now
  378. logger.warning(
  379. f"[{self._id}] _exec_command: unexpected result type {type(result).__name__}, returning as string"
  380. )
  381. return str(result) if result else "", 0
  382. except Exception as e:
  383. logger.error(f"[{self._id}] _exec_command FAILED: {e}")
  384. return f"Error: {e}", -1
  385. # SandboxBackendProtocol implementation
  386. def ls_info(self, path: str) -> list[FileInfo]:
  387. """List files and directories in the specified directory.
  388. Args:
  389. path: Absolute path to directory.
  390. Returns:
  391. List of FileInfo dicts for files and directories.
  392. """
  393. try:
  394. # Use ls command to list files
  395. output, exit_code = self._exec_command(f"ls -la {path}")
  396. if exit_code != 0:
  397. return []
  398. infos: list[FileInfo] = []
  399. lines = output.strip().split("\n")[1:] # Skip "total" line
  400. for line in lines:
  401. parts = line.split()
  402. if len(parts) < 9:
  403. continue
  404. permissions = parts[0]
  405. size = int(parts[4]) if parts[4].isdigit() else 0
  406. name = " ".join(parts[8:])
  407. # Skip . and ..
  408. if name in (".", ".."):
  409. continue
  410. file_path = f"{path.rstrip('/')}/{name}"
  411. is_dir = permissions.startswith("d")
  412. infos.append(
  413. {
  414. "path": file_path + ("/" if is_dir else ""),
  415. "is_dir": is_dir,
  416. "size": size,
  417. "modified_at": "",
  418. }
  419. )
  420. return infos
  421. except Exception as e:
  422. logger.error(f"Failed to list directory {path}: {e}")
  423. return []
  424. def read(
  425. self,
  426. file_path: str,
  427. offset: int = 0,
  428. limit: int = 2000,
  429. ) -> str:
  430. """Read file content with line numbers.
  431. Uses DockerSandbox.read() which leverages Docker's get_archive API
  432. for reliable file reading with intelligent encoding detection.
  433. Args:
  434. file_path: Absolute file path
  435. offset: Line offset to start reading from (0-indexed)
  436. limit: Maximum number of lines to read
  437. Returns:
  438. Formatted file content with line numbers, or error message.
  439. """
  440. logger.info(f"[{self._id}] Reading file: {file_path}")
  441. try:
  442. content = self.raw_read(file_path, offset=0, limit=100000)
  443. if content.startswith("[Error:") or content.startswith("Error:"):
  444. return content
  445. # Format with line numbers using deepagents utility
  446. lines = content.splitlines()
  447. file_data = {
  448. "content": lines,
  449. "created_at": datetime.now().isoformat(),
  450. "modified_at": datetime.now().isoformat(),
  451. }
  452. result: str = format_read_response(file_data, offset, limit)
  453. return result
  454. except Exception as e:
  455. logger.error(f"[{self._id}] Failed to read file {file_path}: {e}")
  456. return f"Error: {str(e)}"
  457. def raw_read(
  458. self,
  459. file_path: str,
  460. offset: int = 0,
  461. limit: int = 100000,
  462. ) -> str:
  463. """Read raw file content without injecting line numbers.
  464. This is intended for UI/API consumers that need the original file text
  465. and will handle presentation concerns such as line-number gutters.
  466. """
  467. logger.info(f"[{self._id}] Raw reading file: {file_path}")
  468. content_raw = self._sandbox.read(file_path, offset=offset, limit=limit)
  469. content = content_raw if isinstance(content_raw, str) else str(content_raw)
  470. if content.startswith("[Error:") or content.startswith("Error:"):
  471. return content
  472. # Remove upstream pagination footer to keep API consumers on raw file text.
  473. if "\n\n[..." in content:
  474. content = content.split("\n\n[...")[0]
  475. return content
  476. def write(
  477. self,
  478. file_path: str,
  479. content: str | bytes,
  480. ) -> WriteResult:
  481. """Create a new file with content.
  482. Uses DockerSandbox.write() which leverages Docker's put_archive API
  483. for reliable file writing without shell command length limits.
  484. Accepts both str and bytes (upstream DockerSandbox supports both).
  485. Args:
  486. file_path: Absolute file path
  487. content: File content (text or binary)
  488. Returns:
  489. WriteResult with success or error.
  490. """
  491. logger.info(f"[{self._id}] Writing file: {file_path}")
  492. try:
  493. # Check if file already exists
  494. check_result = self._exec_command(f"test -f {file_path}")
  495. if check_result[1] == 0: # exit_code == 0 means file exists
  496. return WriteResult(
  497. error=f"Cannot write to {file_path} because it already exists. "
  498. "Read and then make an edit, or write to a new path."
  499. )
  500. result = self._sandbox.write(file_path, content)
  501. if hasattr(result, "error") and result.error:
  502. return WriteResult(error=result.error)
  503. return WriteResult(path=file_path, files_update=None)
  504. except Exception as e:
  505. logger.error(f"[{self._id}] Failed to write file {file_path}: {e}")
  506. return WriteResult(error=f"Failed to write file: {str(e)}")
  507. def write_overwrite(
  508. self,
  509. file_path: str,
  510. content: str | bytes,
  511. ) -> WriteResult:
  512. """Write a file, overwriting if it already exists.
  513. Uses DockerSandbox.write() which leverages Docker's put_archive API
  514. for reliable file writing without shell command length limits.
  515. Accepts both str and bytes (upstream DockerSandbox supports both).
  516. Args:
  517. file_path: Absolute file path
  518. content: File content (text or binary)
  519. Returns:
  520. WriteResult with success or error.
  521. """
  522. logger.debug(f"[{self._id}] write_overwrite: {file_path}")
  523. try:
  524. # Use upstream DockerSandbox.write() which uses Docker put_archive API
  525. # This handles large files and special characters reliably
  526. result = self._sandbox.write(file_path, content)
  527. # Convert upstream WriteResult to deepagents WriteResult
  528. if hasattr(result, "error") and result.error:
  529. return WriteResult(error=result.error)
  530. return WriteResult(path=file_path, files_update=None)
  531. except Exception as e:
  532. logger.error(f"[{self._id}] Failed to write file {file_path}: {e}")
  533. return WriteResult(error=f"Failed to write file: {str(e)}")
  534. def delete(self, file_path: str) -> bool:
  535. """Delete a file inside the container.
  536. Args:
  537. file_path: Absolute file path inside the container.
  538. Returns:
  539. True if deleted successfully, False otherwise.
  540. """
  541. import shlex
  542. logger.debug(f"[{self._id}] Deleting file: {file_path}")
  543. try:
  544. _, exit_code = self._exec_command(f"rm -f {shlex.quote(file_path)}")
  545. return exit_code == 0
  546. except Exception as e:
  547. logger.error(f"[{self._id}] Failed to delete file {file_path}: {e}")
  548. return False
  549. def mkdir(self, dir_path: str) -> bool:
  550. """Create a directory (and parents) inside the container.
  551. Args:
  552. dir_path: Absolute directory path inside the container.
  553. Returns:
  554. True if created successfully, False otherwise.
  555. """
  556. import shlex
  557. logger.debug(f"[{self._id}] Creating directory: {dir_path}")
  558. try:
  559. _, exit_code = self._exec_command(f"mkdir -p {shlex.quote(dir_path)}")
  560. return exit_code == 0
  561. except Exception as e:
  562. logger.error(f"[{self._id}] Failed to create directory {dir_path}: {e}")
  563. return False
  564. def edit(
  565. self,
  566. file_path: str,
  567. old_string: str,
  568. new_string: str,
  569. replace_all: bool = False,
  570. ) -> EditResult:
  571. """Edit a file by replacing string occurrences.
  572. Uses DockerSandbox.edit() which performs in-memory string replacement
  573. and writes back using Docker's put_archive API.
  574. Args:
  575. file_path: Absolute file path
  576. old_string: String to replace
  577. new_string: Replacement string
  578. replace_all: Replace all occurrences (default: False)
  579. Returns:
  580. EditResult with success or error.
  581. """
  582. logger.info(f"[{self._id}] Editing file: {file_path}")
  583. try:
  584. # Use upstream DockerSandbox.edit() which:
  585. # 1. Reads file using Docker get_archive API
  586. # 2. Performs in-memory string replacement
  587. # 3. Writes back using Docker put_archive API
  588. result = self._sandbox.edit(file_path, old_string, new_string, replace_all)
  589. # Convert upstream EditResult to deepagents EditResult
  590. if hasattr(result, "error") and result.error:
  591. return EditResult(error=result.error)
  592. return EditResult(
  593. path=getattr(result, "path", file_path),
  594. files_update=None,
  595. occurrences=getattr(result, "occurrences", 1),
  596. )
  597. except Exception as e:
  598. logger.error(f"[{self._id}] Failed to edit file {file_path}: {e}")
  599. return EditResult(error=f"Failed to edit file: {str(e)}")
  600. def grep_raw(
  601. self,
  602. pattern: str,
  603. path: str | None = None,
  604. glob: str | None = None,
  605. ) -> list[GrepMatch] | str:
  606. """Search for a pattern in files.
  607. Args:
  608. pattern: Search pattern (literal string)
  609. path: Directory to search in (default: working_dir)
  610. glob: Glob pattern to filter files
  611. Returns:
  612. List of GrepMatch dicts or error string.
  613. """
  614. logger.info(f"[{self._id}] Grepping for pattern: {pattern}")
  615. search_path = path or self.working_dir
  616. grep_cmd = f"grep -rn '{pattern}' {search_path}"
  617. if glob:
  618. grep_cmd += f" --include='{glob}'"
  619. output, exit_code = self._exec_command(grep_cmd)
  620. if exit_code != 0 and not output:
  621. return []
  622. matches: list[GrepMatch] = []
  623. for line in output.strip().split("\n"):
  624. if not line:
  625. continue
  626. parts = line.split(":", 2)
  627. if len(parts) >= 3:
  628. matches.append(
  629. {
  630. "path": parts[0],
  631. "line": int(parts[1]) if parts[1].isdigit() else 0,
  632. "text": parts[2],
  633. }
  634. )
  635. return matches
  636. def glob_info(self, pattern: str, path: str = "/") -> list[FileInfo]:
  637. """Find files matching a glob pattern.
  638. Args:
  639. pattern: Glob pattern (e.g., "*.py", "**/*.txt")
  640. path: Directory to search in
  641. Returns:
  642. List of FileInfo dicts for matching files.
  643. """
  644. logger.info(f"[{self._id}] Globbing for pattern: {pattern}")
  645. # Use find command with pattern
  646. find_cmd = f"find {path} -name '{pattern}'"
  647. output, exit_code = self._exec_command(find_cmd)
  648. if exit_code != 0:
  649. return []
  650. infos: list[FileInfo] = []
  651. for file_path in output.strip().split("\n"):
  652. if not file_path:
  653. continue
  654. # Get file size
  655. size_cmd = f"stat -c %s {file_path}"
  656. size_output, _ = self._exec_command(size_cmd)
  657. size = int(size_output.strip()) if size_output.strip().isdigit() else 0
  658. infos.append(
  659. {
  660. "path": file_path,
  661. "is_dir": False,
  662. "size": size,
  663. "modified_at": "",
  664. }
  665. )
  666. return infos
  667. def execute(self, command: str) -> ExecuteResponse:
  668. """Execute a shell command in the container.
  669. Args:
  670. command: Shell command to execute.
  671. Returns:
  672. ExecuteResponse with output, exit code, and truncation flag.
  673. """
  674. logger.info(f"[{self._id}] execute() called: {command[:100]}...")
  675. try:
  676. # Execute command with timeout
  677. output, exit_code = self._exec_command(command)
  678. # Create response with automatic truncation
  679. response = create_execute_response(
  680. output=output,
  681. exit_code=exit_code,
  682. max_output_size=self.max_output_size,
  683. )
  684. if response.truncated:
  685. logger.debug(
  686. f"[{self._id}] Output truncated: {len(output)} -> "
  687. f"{len(response.output)} chars (max={self.max_output_size})"
  688. )
  689. logger.debug(
  690. f"[{self._id}] Command execution completed: exit_code={exit_code}, truncated={response.truncated}"
  691. )
  692. return response
  693. except Exception as e:
  694. logger.error(f"[{self._id}] Error executing command '{command}': {e}", exc_info=True)
  695. return ExecuteResponse(
  696. output=f"Error executing command: {str(e)}",
  697. exit_code=-1,
  698. truncated=False,
  699. )
  700. def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
  701. """Download multiple files from the Docker sandbox using native API.
  702. Args:
  703. paths: List of file paths to download.
  704. Returns:
  705. List of FileDownloadResponse objects, one per input path.
  706. """
  707. responses: list[FileDownloadResponse] = []
  708. for path in paths:
  709. try:
  710. result = self.execute(f"cat {path}")
  711. if result.exit_code == 0:
  712. responses.append(FileDownloadResponse(path=path, content=result.output.encode("utf-8"), error=None))
  713. else:
  714. responses.append(FileDownloadResponse(path=path, content=None, error="file_not_found"))
  715. except Exception as e:
  716. logger.error(f"Failed to download file {path}: {e}")
  717. responses.append(FileDownloadResponse(path=path, content=None, error="permission_denied"))
  718. return responses
  719. def _collect_file_paths(self, dir_path: str, base: str, out: List[str]) -> None:
  720. """Recursively collect all file paths under dir_path (relative to base)."""
  721. infos = self.ls_info(dir_path)
  722. for info in infos:
  723. path = (info.get("path") or "").rstrip("/")
  724. if not path:
  725. continue
  726. is_dir = info.get("is_dir", False)
  727. if is_dir:
  728. self._collect_file_paths(path, base, out)
  729. else:
  730. if path.startswith(base):
  731. rel = path[len(base) :].lstrip("/")
  732. if rel:
  733. out.append(path)
  734. def export_working_dir_to(self, target_dir: Path) -> int:
  735. """Export all files from the container working directory to target_dir.
  736. Preserves directory structure. Returns the number of files written.
  737. """
  738. target_dir = Path(target_dir).resolve()
  739. target_dir.mkdir(parents=True, exist_ok=True)
  740. base = self.working_dir.rstrip("/")
  741. if not base:
  742. base = "/"
  743. paths: List[str] = []
  744. self._collect_file_paths(base, base, paths)
  745. if not paths:
  746. return 0
  747. responses = self.download_files(paths)
  748. written = 0
  749. for resp in responses:
  750. if resp.error or resp.content is None:
  751. continue
  752. path = resp.path
  753. if path.startswith(base):
  754. rel = path[len(base) :].lstrip("/")
  755. else:
  756. rel = Path(path).name
  757. dest = target_dir / rel
  758. dest.parent.mkdir(parents=True, exist_ok=True)
  759. try:
  760. dest.write_bytes(resp.content)
  761. written += 1
  762. except Exception as e:
  763. logger.warning(f"[PydanticSandboxAdapter] Failed to write {dest}: {e}")
  764. return written
  765. def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
  766. """Upload multiple files to the Docker sandbox using base64 encoding.
  767. Args:
  768. files: List of (path, content) tuples to upload.
  769. Returns:
  770. List of FileUploadResponse objects, one per input file.
  771. """
  772. import base64
  773. responses: list[FileUploadResponse] = []
  774. for path, content in files:
  775. try:
  776. encoded = base64.b64encode(content).decode("ascii")
  777. _, exit_code = self._exec_command(f"echo '{encoded}' | base64 -d > {path}")
  778. if exit_code == 0:
  779. responses.append(FileUploadResponse(path=path, error=None))
  780. else:
  781. responses.append(FileUploadResponse(path=path, error="permission_denied"))
  782. except Exception as e:
  783. logger.error(f"Failed to upload file {path}: {e}")
  784. responses.append(FileUploadResponse(path=path, error="permission_denied"))
  785. return responses
  786. @staticmethod
  787. def _force_remove_container(container_id: str) -> None:
  788. """Force-remove a Docker container by ID, ignoring all errors."""
  789. try:
  790. from app.core.agent.backends.docker_check import get_docker_client
  791. get_docker_client().containers.get(container_id).remove(force=True)
  792. logger.info(f"Force-removed stale container {container_id[:12]}")
  793. except Exception as e:
  794. logger.warning(f"Could not remove stale container {container_id[:12]}: {e}")
  795. def stop(self) -> None:
  796. """Stop the Docker container without removing it. Idempotent.
  797. IMPORTANT: This only stops the container. It does NOT remove it.
  798. After stop(), start() can restart the same container via _saved_container_id.
  799. Never falls back to cleanup() which would destroy the container.
  800. """
  801. if not self._started:
  802. return
  803. # Save container_id BEFORE stopping so we can restart later
  804. upstream_container = getattr(self._sandbox, "_container", None)
  805. if upstream_container is not None:
  806. self._saved_container_id = getattr(upstream_container, "id", None)
  807. try:
  808. if hasattr(self._sandbox, "stop"):
  809. self._sandbox.stop()
  810. elif upstream_container is not None and hasattr(upstream_container, "stop"):
  811. # Direct Docker API: stop container without removing
  812. upstream_container.stop()
  813. else:
  814. # No stop method available; just mark as stopped
  815. logger.warning(
  816. f"Sandbox {self._id}: no stop() method available, marking as stopped but container may still run"
  817. )
  818. logger.info(f"Sandbox {self._id} stopped (container kept, id={self._saved_container_id})")
  819. except Exception as e:
  820. logger.warning(f"Failed to stop sandbox {self._id}: {e}")
  821. finally:
  822. self._started = False
  823. def cleanup(self) -> None:
  824. """Stop and remove the Docker container. Idempotent. Use for rebuild/teardown only.
  825. Sequence:
  826. 1. Save container_id from live container reference
  827. 2. Stop the container (sets _started=False, saves _saved_container_id)
  828. 3. Remove the container using saved references
  829. """
  830. # Save container reference BEFORE stop() clears it
  831. pre_stop_container = getattr(self._sandbox, "_container", None) if getattr(self, "_sandbox", None) else None
  832. pre_stop_container_id = getattr(pre_stop_container, "id", None) if pre_stop_container else None
  833. self.stop()
  834. if getattr(self, "_sandbox", None) is None:
  835. self._saved_container_id = None
  836. return
  837. # Determine which container ID to remove
  838. container_id_to_remove = self._saved_container_id or pre_stop_container_id
  839. try:
  840. # Try direct container reference first (may still be on _sandbox after stop)
  841. container = getattr(self._sandbox, "container", None) or getattr(self._sandbox, "_container", None)
  842. if container is not None and hasattr(container, "remove"):
  843. container.remove(force=True)
  844. logger.info(f"Sandbox {self._id} container removed (direct ref)")
  845. elif container_id_to_remove:
  846. from app.core.agent.backends.docker_check import get_docker_client
  847. client = get_docker_client()
  848. client.containers.get(container_id_to_remove).remove(force=True)
  849. logger.info(f"Sandbox {self._id} container removed (by id={container_id_to_remove[:12]})")
  850. elif hasattr(self._sandbox, "remove"):
  851. self._sandbox.remove()
  852. logger.info(f"Sandbox {self._id} container removed (sandbox.remove)")
  853. else:
  854. logger.warning(f"Sandbox {self._id}: no way to remove container")
  855. except Exception as e:
  856. logger.warning(f"Failed to remove sandbox container {self._id}: {e}")
  857. finally:
  858. self._saved_container_id = None
  859. # NOTE: __del__ is intentionally NOT implemented.
  860. # GC-time cleanup of Docker containers causes unpredictable behavior:
  861. # - May delete containers still tracked by the pool
  862. # - May run after event loop is closed
  863. # - Interferes with the pool-based lifecycle management
  864. # All cleanup must be explicit via cleanup() or the SandboxPool.
  865. def __enter__(self):
  866. """Context manager entry."""
  867. return self
  868. def __exit__(self, exc_type, exc_val, exc_tb):
  869. """Context manager exit."""
  870. self.cleanup()
backend/app/core/agent/code_agent/executor/router.py ยท Bundled script ยท 315 lines ยท 1 finding marked
  1. #!/usr/bin/env python
  2. """
  3. Executor Router for CodeAgent.
  4. This module implements intelligent routing between different Python executors
  5. based on code analysis and security requirements.
  6. """
  7. import re
  8. from typing import Any, Callable, Optional
  9. from loguru import logger
  10. from .base import CodeOutput, PythonExecutor
  11. from .local_executor import LocalPythonExecutor
  12. # Patterns that indicate potentially dangerous code
  13. DANGEROUS_PATTERNS = [
  14. # System/OS access
  15. (r"\bimport\s+os\b", "os module import"),
  16. (r"\bimport\s+subprocess\b", "subprocess module import"),
  17. (r"\bimport\s+sys\b", "sys module import"),
  18. (r"\bimport\s+socket\b", "socket module import"),
  19. (r"\bimport\s+shutil\b", "shutil module import"),
  20. # File operations with write mode
  21. (r"\bopen\s*\([^)]*['\"][wa]", "file write operation"),
  22. (r"\bopen\s*\([^)]*mode\s*=\s*['\"][wa]", "file write operation"),
  23. # Network requests
  24. (r"\brequests\.", "requests library usage"),
  25. (r"\burllib\.", "urllib library usage"),
  26. (r"\bhttpx\.", "httpx library usage"),
  27. (r"\baiohttp\.", "aiohttp library usage"),
  28. # Code execution
  29. (r"\beval\s*\(", "eval() call"),
  30. (r"\bexec\s*\(", "exec() call"),
  31. (r"\bcompile\s*\(", "compile() call"),
  32. (r"\b__import__\s*\(", "__import__() call"),
  33. # Shell commands
  34. (r"\bos\.system\s*\(", "os.system() call"),
  35. (r"\bos\.popen\s*\(", "os.popen() call"),
  36. (r"\bsubprocess\.", "subprocess usage"),
  37. # Dunder access
  38. (r"__\w+__\s*(?:\[|\.)", "dunder attribute access"),
  39. # Pickle (arbitrary code execution)
  40. (r"\bpickle\.load", "pickle deserialization"),
  41. (r"\bcPickle\.load", "pickle deserialization"),
  42. ]
  43. # Patterns that suggest data analysis (safe for local execution)
  44. DATA_ANALYSIS_PATTERNS = [
  45. r"\bimport\s+pandas\b",
  46. r"\bimport\s+numpy\b",
  47. r"\bimport\s+matplotlib\b",
  48. r"\bimport\s+seaborn\b",
  49. r"\bimport\s+sklearn\b",
  50. r"\bimport\s+scipy\b",
  51. r"\bpd\.",
  52. r"\bnp\.",
  53. r"\bplt\.",
  54. ]
  55. class SecurityError(Exception):
  56. """Exception raised when dangerous code is detected."""
  57. pass
  58. class ExecutorRouter:
  59. """
  60. Routes code execution to appropriate executor based on analysis.
  61. The router analyzes code to determine:
  62. 1. Is the code safe for local AST interpretation?
  63. 2. Does it require Docker isolation?
  64. 3. Should it be blocked entirely?
  65. Features:
  66. - Pattern-based danger detection
  67. - Configurable routing policies
  68. - Fallback handling
  69. - Execution metrics
  70. Example:
  71. >>> router = ExecutorRouter(
  72. ... local=LocalPythonExecutor(),
  73. ... docker=DockerPythonExecutor(),
  74. ... )
  75. >>> result = router("import pandas; df = pd.read_csv('data.csv')")
  76. # Routes to local executor (safe data analysis)
  77. >>> result = router("import os; os.system('rm -rf /')")
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 92 on GitHub
  78. # Routes to Docker executor (dangerous but allowed in sandbox)
  79. """
  80. def __init__(
  81. self,
  82. local: Optional[PythonExecutor] = None,
  83. docker: Optional[PythonExecutor] = None,
  84. allow_dangerous: bool = False,
  85. prefer_docker: bool = False,
  86. dangerous_patterns: Optional[list[tuple[str, str]]] = None,
  87. ):
  88. """
  89. Initialize the executor router.
  90. Args:
  91. local: Local Python executor (AST-based).
  92. docker: Docker Python executor.
  93. allow_dangerous: Allow dangerous code (routes to Docker).
  94. prefer_docker: Always prefer Docker when available.
  95. dangerous_patterns: Custom dangerous patterns to check.
  96. """
  97. self.local = local or LocalPythonExecutor()
  98. self.docker = docker
  99. self.allow_dangerous = allow_dangerous
  100. self.prefer_docker = prefer_docker
  101. self.dangerous_patterns = dangerous_patterns or DANGEROUS_PATTERNS
  102. # Metrics
  103. self._local_count = 0
  104. self._docker_count = 0
  105. self._blocked_count = 0
  106. logger.info(
  107. f"ExecutorRouter initialized: local={type(self.local).__name__}, "
  108. f"docker={type(self.docker).__name__ if self.docker else 'None'}, "
  109. f"allow_dangerous={allow_dangerous}"
  110. )
  111. def analyze_code(self, code: str) -> dict[str, Any]:
  112. """
  113. Analyze code for routing decisions.
  114. Args:
  115. code: The Python code to analyze.
  116. Returns:
  117. Analysis result with danger level and details.
  118. """
  119. dangers = []
  120. for pattern, description in self.dangerous_patterns:
  121. if re.search(pattern, code, re.IGNORECASE):
  122. dangers.append(description)
  123. # Check for data analysis (considered safe)
  124. is_data_analysis = any(re.search(pattern, code, re.IGNORECASE) for pattern in DATA_ANALYSIS_PATTERNS)
  125. return {
  126. "is_dangerous": len(dangers) > 0,
  127. "dangers": dangers,
  128. "is_data_analysis": is_data_analysis,
  129. "danger_level": len(dangers),
  130. }
  131. def route(self, code: str) -> PythonExecutor:
  132. """
  133. Determine which executor to use for the code.
  134. Args:
  135. code: The Python code to route.
  136. Returns:
  137. The appropriate executor.
  138. Raises:
  139. SecurityError: If dangerous code is not allowed.
  140. """
  141. # Always prefer Docker if configured
  142. if self.prefer_docker and self.docker is not None:
  143. logger.debug("Routing to Docker executor (prefer_docker=True)")
  144. return self.docker # type: ignore[return-value]
  145. # Analyze code
  146. analysis = self.analyze_code(code)
  147. if analysis["is_dangerous"]:
  148. dangers = ", ".join(analysis["dangers"])
  149. logger.warning(f"Dangerous code detected: {dangers}")
  150. if self.docker is not None:
  151. logger.info("Routing dangerous code to Docker executor")
  152. return self.docker # type: ignore[return-value]
  153. elif self.allow_dangerous:
  154. logger.warning("No Docker available, executing dangerous code locally")
  155. return self.local
  156. else:
  157. self._blocked_count += 1
  158. raise SecurityError(
  159. f"Dangerous code patterns detected: {dangers}. "
  160. "Configure a Docker executor or set allow_dangerous=True."
  161. )
  162. # Safe code - use local executor
  163. logger.debug("Routing to local executor (safe code)")
  164. return self.local
  165. def __call__(
  166. self,
  167. code: str,
  168. additional_tools: Optional[dict[str, Callable]] = None,
  169. ) -> CodeOutput:
  170. """
  171. Execute code using the appropriate executor.
  172. Args:
  173. code: The Python code to execute.
  174. additional_tools: Optional additional tools.
  175. Returns:
  176. CodeOutput from the execution.
  177. """
  178. try:
  179. executor = self.route(code)
  180. if executor is self.local:
  181. self._local_count += 1
  182. else:
  183. self._docker_count += 1
  184. return executor(code, additional_tools)
  185. except SecurityError as e:
  186. return CodeOutput(error=str(e))
  187. def send_tools(self, tools: dict[str, Callable]) -> None:
  188. """Send tools to both executors."""
  189. self.local.send_tools(tools)
  190. if self.docker:
  191. self.docker.send_tools(tools)
  192. def send_variables(self, variables: dict[str, Any]) -> None:
  193. """Send variables to both executors."""
  194. self.local.send_variables(variables)
  195. if self.docker:
  196. self.docker.send_variables(variables)
  197. def reset(self) -> None:
  198. """Reset both executors."""
  199. self.local.reset()
  200. if self.docker:
  201. self.docker.reset()
  202. def cleanup(self) -> None:
  203. """Cleanup both executors."""
  204. self.local.cleanup()
  205. if self.docker:
  206. self.docker.cleanup()
  207. def get_metrics(self) -> dict[str, int]:
  208. """Get routing metrics."""
  209. return {
  210. "local_executions": self._local_count,
  211. "docker_executions": self._docker_count,
  212. "blocked_executions": self._blocked_count,
  213. "total_executions": self._local_count + self._docker_count,
  214. }
  215. def __repr__(self) -> str:
  216. return (
  217. f"ExecutorRouter("
  218. f"local={type(self.local).__name__}, "
  219. f"docker={type(self.docker).__name__ if self.docker else 'None'}, "
  220. f"metrics={self.get_metrics()}"
  221. f")"
  222. )
  223. def create_router(
  224. enable_docker: bool = True,
  225. allow_dangerous: bool = False,
  226. prefer_docker: bool = False,
  227. docker_kwargs: Optional[dict[Any, Any]] = None,
  228. local_kwargs: Optional[dict[Any, Any]] = None,
  229. ) -> ExecutorRouter:
  230. """
  231. Factory function to create a configured ExecutorRouter.
  232. Args:
  233. enable_docker: Enable Docker executor.
  234. allow_dangerous: Allow dangerous code.
  235. prefer_docker: Always prefer Docker.
  236. docker_kwargs: Arguments for DockerPythonExecutor.
  237. local_kwargs: Arguments for LocalPythonExecutor.
  238. Returns:
  239. Configured ExecutorRouter instance.
  240. """
  241. local = LocalPythonExecutor(**(local_kwargs or {}))
  242. docker = None
  243. if enable_docker:
  244. try:
  245. from .docker_executor import DockerPythonExecutor
  246. docker = DockerPythonExecutor(**(docker_kwargs or {}))
  247. except Exception as e:
  248. logger.warning(f"Failed to initialize Docker executor: {e}")
  249. return ExecutorRouter(
  250. local=local,
  251. docker=docker,
  252. allow_dangerous=allow_dangerous,
  253. prefer_docker=prefer_docker,
  254. )
  255. __all__ = [
  256. "SecurityError",
  257. "ExecutorRouter",
  258. "create_router",
  259. "DANGEROUS_PATTERNS",
  260. "DATA_ANALYSIS_PATTERNS",
  261. ]

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If itโ€™s helped, pass it on.