codeshield-runtime 0.1.2__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/LICENSE +1 -1
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/PKG-INFO +105 -29
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/README.md +103 -27
- codeshield_runtime-0.2.0/SECURITY.md +31 -0
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/pyproject.toml +6 -2
- codeshield_runtime-0.2.0/src/codeshield/__init__.py +48 -0
- codeshield_runtime-0.2.0/src/codeshield/analyzer.py +417 -0
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/src/codeshield/classifier.py +7 -2
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/src/codeshield/cli.py +24 -6
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/src/codeshield/environment.py +80 -10
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/src/codeshield/loop.py +55 -30
- codeshield_runtime-0.2.0/src/codeshield/runner.py +376 -0
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/src/codeshield/schemas.py +215 -120
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/src/codeshield/tools.py +31 -10
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/tests/test_coverage.py +11 -7
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/tests/test_engine.py +8 -7
- codeshield_runtime-0.2.0/tests/test_security.py +308 -0
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/tests/test_tools.py +10 -2
- codeshield_runtime-0.1.2/src/codeshield/__init__.py +0 -17
- codeshield_runtime-0.1.2/src/codeshield/analyzer.py +0 -151
- codeshield_runtime-0.1.2/src/codeshield/runner.py +0 -221
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/.gitignore +0 -0
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/src/codeshield/__main__.py +0 -0
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/tests/__init__.py +0 -0
- {codeshield_runtime-0.1.2 → codeshield_runtime-0.2.0}/tests/test_cli.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2026
|
|
3
|
+
Copyright (c) 2026 AlgorithmicMind (CodeShield contributors)
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: codeshield-runtime
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: A secure, isolated, and self-healing Python code execution engine powered by uv and AST analysis.
|
|
5
5
|
Project-URL: Homepage, https://github.com/AlgorithmicMind/codeshield
|
|
6
6
|
Project-URL: Repository, https://github.com/AlgorithmicMind/codeshield
|
|
7
7
|
Project-URL: Issues, https://github.com/AlgorithmicMind/codeshield/issues
|
|
8
|
-
Author:
|
|
8
|
+
Author: AlgorithmicMind
|
|
9
9
|
License: MIT
|
|
10
10
|
License-File: LICENSE
|
|
11
11
|
Keywords: ast,code,execution,sandbox,self-healing,uv
|
|
@@ -37,9 +37,11 @@ Description-Content-Type: text/markdown
|
|
|
37
37
|
# CodeShield: Autonomous Code Execution Engine
|
|
38
38
|
|
|
39
39
|
[](https://github.com/AlgorithmicMind/codeshield/actions)
|
|
40
|
-
[](https://www.python.org/)
|
|
41
41
|
[](LICENSE)
|
|
42
42
|
[](https://github.com/astral-sh/ruff)
|
|
43
|
+
[](https://pypi.org/project/codeshield-runtime/)
|
|
44
|
+
[](https://pypi.org/project/codeshield-runtime/)
|
|
43
45
|
|
|
44
46
|
> Deterministic, Isolated, and Self-Healing Python Execution Runtime for AI Agents.
|
|
45
47
|
|
|
@@ -50,8 +52,8 @@ This open-source engine executes Python code generated by LLMs inside a disposab
|
|
|
50
52
|
| Feature | Vanilla `subprocess` | Docker Container | CodeShield (This Engine) |
|
|
51
53
|
| :--- | :--- | :--- | :--- |
|
|
52
54
|
| **Startup Overhead** | ~5 – 10 ms | ~1,500 – 3,000 ms | **Sub-second (~30–250 ms via `uv`)** |
|
|
53
|
-
| **Isolation Mechanism** | None (Host Process) | Container Namespaces / cgroups | **Ephemeral Virtualenv
|
|
54
|
-
| **AST Security Gate** | ❌ None | ❌ None | **✅
|
|
55
|
+
| **Isolation Mechanism** | None (Host Process) | Container Namespaces / cgroups | **Ephemeral Virtualenv + Env Allowlist + Scoped `cwd` + Tree Kill** |
|
|
56
|
+
| **AST Security Gate** | ❌ None | ❌ None | **✅ Fail-closed AST gate (aliases, dunders, blocked modules, dangerous calls)** |
|
|
55
57
|
| **Silent Failure Detection** | ❌ None | ❌ None | **✅ Regex scanning for empty DataFrames/NaNs** |
|
|
56
58
|
| **Self-Healing Loop** | ❌ None | ❌ None | **✅ 3-Tier Traceback Diagnosis + LLM Patch (Any Provider)** |
|
|
57
59
|
|
|
@@ -77,20 +79,21 @@ This open-source engine executes Python code generated by LLMs inside a disposab
|
|
|
77
79
|
|
|
78
80
|
## Key Features
|
|
79
81
|
|
|
80
|
-
### 1. Ephemeral Sandboxing with
|
|
82
|
+
### 1. Ephemeral Sandboxing with Hardened Subprocess Controls
|
|
81
83
|
|
|
82
|
-
- **Primary**: `uv venv` for ultra-fast environment creation and package installation.
|
|
83
|
-
- **
|
|
84
|
-
-
|
|
84
|
+
- **Primary**: `uv venv` for ultra-fast environment creation and package installation, with native `python -m venv` + `pip` fallback.
|
|
85
|
+
- **Minimal Environment Allowlist**: host secrets (`GEMINI_API_KEY`, cloud tokens, `.env` values) are **never** inherited by the child process. Pass explicit variables via `CodeExecutionRequest(env={...})` or `SubprocessRunner(env_allowlist=[...])`.
|
|
86
|
+
- **Workspace & Resource Guardrails**: scripts execute with `cwd` and temp directories pinned inside the disposable workspace, strict path-traversal & PEP 508 package validation, bounded `stdout`/`stderr` capture (`max_output_bytes`), redacted host paths in tracebacks, and process-tree termination on timeout.
|
|
85
87
|
|
|
86
|
-
### 2.
|
|
88
|
+
### 2. Fail-Closed AST Security Gates
|
|
87
89
|
|
|
88
|
-
The engine parses every snippet with the standard `ast` module and
|
|
90
|
+
The engine parses every snippet (and every LLM-generated patch) with the standard `ast` module and fails closed on:
|
|
89
91
|
|
|
90
92
|
- `SyntaxError`s before execution.
|
|
91
|
-
- Bare `except:` / `except Exception:` / `except BaseException:` handlers.
|
|
92
|
-
-
|
|
93
|
-
-
|
|
93
|
+
- Bare `except:` / `except Exception:` / `except BaseException:` handlers (including tuple handlers).
|
|
94
|
+
- Dangerous builtins & reflection (`eval()`, `exec()`, `compile()`, `__import__()`, `getattr()`, `globals()`, etc.) even when aliased or reassigned.
|
|
95
|
+
- Blocked high-risk modules (`subprocess`, `ctypes`, `importlib`, `pickle`, `socket`, `shutil`, `builtins`, etc.) and dangerous `os`/`sys` APIs (`os.system`, `os.popen`, `os.environ`, `sys.modules`, `sys._getframe`).
|
|
96
|
+
- Reflection dunder traversal (`__subclasses__`, `__builtins__`, `__globals__`, `__class__`, `__bases__`, etc.).
|
|
94
97
|
|
|
95
98
|
### 3. Silent Failure Detection
|
|
96
99
|
|
|
@@ -110,7 +113,7 @@ AST Validation ──► Sandbox Execution ──► Traceback Classification
|
|
|
110
113
|
```
|
|
111
114
|
|
|
112
115
|
- **Local heuristic fallback**: handles `NameError`, `ImportError`, `ModuleNotFoundError` by injecting safe imports or placeholder definitions.
|
|
113
|
-
- **LLM-guided healing**: when an LLM is configured (built-in Gemini
|
|
116
|
+
- **LLM-guided healing**: when an LLM is configured (built-in Gemini 4 by default, or any custom provider via `patch_generator`), it asks the model for a corrected version of the code, validates it with the AST gate, and re-executes the patched snippet.
|
|
114
117
|
|
|
115
118
|
---
|
|
116
119
|
|
|
@@ -142,12 +145,18 @@ pip install -e ".[test,lint,llm,dev]"
|
|
|
142
145
|
### Offline Usage (No API Key)
|
|
143
146
|
|
|
144
147
|
```python
|
|
145
|
-
from codeshield
|
|
148
|
+
from codeshield import SelfHealingEngine
|
|
146
149
|
|
|
150
|
+
# The sandbox is created and destroyed automatically on every ``run`` call.
|
|
147
151
|
engine = SelfHealingEngine(use_llm=False)
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
152
|
+
result, diagnosis = engine.run("print('hello world')")
|
|
153
|
+
print(result.stdout)
|
|
154
|
+
|
|
155
|
+
# Use a ``with`` block to reuse a single sandbox across multiple runs.
|
|
156
|
+
with SelfHealingEngine(use_llm=False) as reusable_engine:
|
|
157
|
+
first, _ = reusable_engine.run("print(1 + 1)")
|
|
158
|
+
second, _ = reusable_engine.run("print(2 + 2)")
|
|
159
|
+
print(first.stdout, second.stdout)
|
|
151
160
|
```
|
|
152
161
|
|
|
153
162
|
### Model-Agnostic Self-Healing (Plug-and-Play)
|
|
@@ -155,13 +164,13 @@ with engine:
|
|
|
155
164
|
CodeShield is not locked into a single LLM. Pass any Python callable as the `patch_generator` to use OpenAI, Anthropic Claude, DeepSeek, Ollama, LiteLLM or your own service:
|
|
156
165
|
|
|
157
166
|
```python
|
|
158
|
-
from codeshield
|
|
167
|
+
from codeshield import SelfHealingEngine
|
|
159
168
|
|
|
160
169
|
|
|
161
170
|
def custom_llm_patcher(code: str, diagnosis) -> str:
|
|
162
|
-
# Compatible with any frontier provider: GPT-5.
|
|
171
|
+
# Compatible with any frontier provider: GPT-5.6, Claude Sonnet 5, DeepSeek V4, Ollama
|
|
163
172
|
response = client.chat.completions.create(
|
|
164
|
-
model="gpt-5.
|
|
173
|
+
model="gpt-5.6-luna", # or "claude-sonnet-5", "deepseek-v4-flash"
|
|
165
174
|
messages=[
|
|
166
175
|
{
|
|
167
176
|
"role": "user",
|
|
@@ -173,20 +182,26 @@ def custom_llm_patcher(code: str, diagnosis) -> str:
|
|
|
173
182
|
|
|
174
183
|
|
|
175
184
|
engine = SelfHealingEngine(patch_generator=custom_llm_patcher)
|
|
185
|
+
|
|
186
|
+
# Broken code -> AST gate -> sandbox execution -> traceback classification ->
|
|
187
|
+
# custom patch -> AST re-validation -> re-execution, all in a single call.
|
|
188
|
+
result, diagnosis = engine.run('print("Result: " + 42)')
|
|
189
|
+
print(result.stdout) # Result: 42
|
|
176
190
|
```
|
|
177
191
|
|
|
178
|
-
### Zero-Config Self-Healing with Gemini
|
|
192
|
+
### Zero-Config Self-Healing with Gemini 4
|
|
179
193
|
|
|
180
194
|
For the built-in zero-config experience, create a `.env` file from `.env.example`:
|
|
181
195
|
|
|
182
196
|
```text
|
|
183
197
|
GEMINI_API_KEY=your_key_here
|
|
184
|
-
GEMINI_MODEL=gemini-
|
|
198
|
+
GEMINI_MODEL=gemini-4-hydrogen
|
|
185
199
|
```
|
|
186
200
|
|
|
187
201
|
```python
|
|
188
202
|
from dotenv import load_dotenv
|
|
189
|
-
|
|
203
|
+
|
|
204
|
+
from codeshield import SelfHealingEngine
|
|
190
205
|
|
|
191
206
|
load_dotenv()
|
|
192
207
|
|
|
@@ -218,12 +233,73 @@ python -m codeshield run script.py --no-llm # force local fallback
|
|
|
218
233
|
```python
|
|
219
234
|
from codeshield import create_code_execution_tool
|
|
220
235
|
|
|
221
|
-
#
|
|
236
|
+
# Standard usage: built-in Gemini healing when configured, local heuristic otherwise
|
|
222
237
|
tools = [create_code_execution_tool()]
|
|
238
|
+
|
|
239
|
+
# Or bring your own model: the patcher is forwarded to the internal engine
|
|
240
|
+
tools = [create_code_execution_tool(patch_generator=custom_llm_patcher)]
|
|
223
241
|
```
|
|
224
242
|
|
|
225
243
|
`create_code_execution_tool()` returns a ready-to-register `execute_python_code(code: str) -> str` function. It runs the provided Python in a self-healing sandbox and returns either the stdout or a structured error report with `error_type` and `stderr`.
|
|
226
244
|
|
|
245
|
+
The callable exposes real type hints and a Google-style docstring, so any SDK that builds a function schema from a plain Python callable can register it directly.
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
## Public API
|
|
250
|
+
|
|
251
|
+
Everything is re-exported at the package root, so imports never need internal submodules:
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
from codeshield import (
|
|
255
|
+
DEFAULT_GEMINI_MODEL,
|
|
256
|
+
ASTSecurityError,
|
|
257
|
+
CodeExecutionRequest,
|
|
258
|
+
ErrorDiagnosis,
|
|
259
|
+
ExecutionResult,
|
|
260
|
+
GeminiPatchGenerator,
|
|
261
|
+
LLMPatchError,
|
|
262
|
+
PatchProposal,
|
|
263
|
+
SandboxError,
|
|
264
|
+
SandboxManager,
|
|
265
|
+
SelfHealingEngine,
|
|
266
|
+
SelfHealingError,
|
|
267
|
+
SubprocessRunner,
|
|
268
|
+
SubprocessRunnerError,
|
|
269
|
+
TracebackClassifier,
|
|
270
|
+
ValidationReport,
|
|
271
|
+
create_code_execution_tool,
|
|
272
|
+
validate_syntax_and_safety,
|
|
273
|
+
)
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
`ASTSecurityError` subclasses `SelfHealingError` and is raised whenever the static AST gate blocks either the original snippet or a generated patch.
|
|
277
|
+
|
|
278
|
+
### Explicit Environment Variables
|
|
279
|
+
|
|
280
|
+
Host environment variables (including API keys loaded from `.env`) are never leaked into executed code. To expose specific variables to a snippet, pass them explicitly:
|
|
281
|
+
|
|
282
|
+
```python
|
|
283
|
+
from codeshield import CodeExecutionRequest, SelfHealingEngine
|
|
284
|
+
|
|
285
|
+
request = CodeExecutionRequest(
|
|
286
|
+
code="import json\nprint(json.dumps({'status': 'ok'}))",
|
|
287
|
+
env={"APP_MODE": "sandbox"},
|
|
288
|
+
)
|
|
289
|
+
with SelfHealingEngine(use_llm=False) as engine:
|
|
290
|
+
result, _ = engine.run(request)
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
295
|
+
## Security Model & Threat Boundaries
|
|
296
|
+
|
|
297
|
+
CodeShield provides **application-layer defense-in-depth** tailored for LLM-generated data, math, and automation snippets (fail-closed AST checks, env allowlisting, scoped workspace `cwd`, path traversal & pip-flag validation, bounded output capture, host-path redaction, and process-tree termination).
|
|
298
|
+
|
|
299
|
+
> **Threat boundary:** Ephemeral virtualenvs and static AST inspection do **not** provide OS kernel isolation (namespaces, seccomp, cgroups, or network firewalls). For **untrusted or adversarial multi-tenant workloads**, run CodeShield inside a hardened container or microVM (Docker with `--network=none --read-only`, gVisor, or Firecracker).
|
|
300
|
+
|
|
301
|
+
See [SECURITY.md](SECURITY.md) for the full security policy and private vulnerability disclosure instructions.
|
|
302
|
+
|
|
227
303
|
---
|
|
228
304
|
|
|
229
305
|
## Verified Examples
|
|
@@ -233,7 +309,7 @@ The `examples/` folder contains ready-to-run recipes that have been executed and
|
|
|
233
309
|
- `01_basic_sandboxing.py`: isolated execution with timing measurements.
|
|
234
310
|
- `02_security_gatekeeper.py`: AST rejection of unsafe code.
|
|
235
311
|
- `03_llm_healing_workflow.py`: self-healing workflow with an LLM or local fallback.
|
|
236
|
-
- `04_agent_tool_dropin.py`:
|
|
312
|
+
- `04_agent_tool_dropin.py`: dual-phase agentic trace, printing agent thought, tool call, sandbox runtime and final answer for both a legitimate analytics round and a security-defense round where the AST gate blocks a shell escape.
|
|
237
313
|
- `05_custom_llm_openai_compatible.py`: model-agnostic, API-key-free self-healing with a custom `patch_generator`.
|
|
238
314
|
|
|
239
315
|
```bash
|
|
@@ -246,10 +322,10 @@ python examples/05_custom_llm_openai_compatible.py
|
|
|
246
322
|
|
|
247
323
|
## Running Tests & Lint
|
|
248
324
|
|
|
249
|
-
The suite currently has **
|
|
325
|
+
The suite currently has **110 tests** with **>85% code coverage** on `src/codeshield`.
|
|
250
326
|
|
|
251
327
|
```bash
|
|
252
|
-
ruff check src tests examples
|
|
328
|
+
ruff check src tests examples demo.py
|
|
253
329
|
pytest tests -v --cov=src/codeshield
|
|
254
330
|
```
|
|
255
331
|
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
# CodeShield: Autonomous Code Execution Engine
|
|
2
2
|
|
|
3
3
|
[](https://github.com/AlgorithmicMind/codeshield/actions)
|
|
4
|
-
[](https://www.python.org/)
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
[](https://github.com/astral-sh/ruff)
|
|
7
|
+
[](https://pypi.org/project/codeshield-runtime/)
|
|
8
|
+
[](https://pypi.org/project/codeshield-runtime/)
|
|
7
9
|
|
|
8
10
|
> Deterministic, Isolated, and Self-Healing Python Execution Runtime for AI Agents.
|
|
9
11
|
|
|
@@ -14,8 +16,8 @@ This open-source engine executes Python code generated by LLMs inside a disposab
|
|
|
14
16
|
| Feature | Vanilla `subprocess` | Docker Container | CodeShield (This Engine) |
|
|
15
17
|
| :--- | :--- | :--- | :--- |
|
|
16
18
|
| **Startup Overhead** | ~5 – 10 ms | ~1,500 – 3,000 ms | **Sub-second (~30–250 ms via `uv`)** |
|
|
17
|
-
| **Isolation Mechanism** | None (Host Process) | Container Namespaces / cgroups | **Ephemeral Virtualenv
|
|
18
|
-
| **AST Security Gate** | ❌ None | ❌ None | **✅
|
|
19
|
+
| **Isolation Mechanism** | None (Host Process) | Container Namespaces / cgroups | **Ephemeral Virtualenv + Env Allowlist + Scoped `cwd` + Tree Kill** |
|
|
20
|
+
| **AST Security Gate** | ❌ None | ❌ None | **✅ Fail-closed AST gate (aliases, dunders, blocked modules, dangerous calls)** |
|
|
19
21
|
| **Silent Failure Detection** | ❌ None | ❌ None | **✅ Regex scanning for empty DataFrames/NaNs** |
|
|
20
22
|
| **Self-Healing Loop** | ❌ None | ❌ None | **✅ 3-Tier Traceback Diagnosis + LLM Patch (Any Provider)** |
|
|
21
23
|
|
|
@@ -41,20 +43,21 @@ This open-source engine executes Python code generated by LLMs inside a disposab
|
|
|
41
43
|
|
|
42
44
|
## Key Features
|
|
43
45
|
|
|
44
|
-
### 1. Ephemeral Sandboxing with
|
|
46
|
+
### 1. Ephemeral Sandboxing with Hardened Subprocess Controls
|
|
45
47
|
|
|
46
|
-
- **Primary**: `uv venv` for ultra-fast environment creation and package installation.
|
|
47
|
-
- **
|
|
48
|
-
-
|
|
48
|
+
- **Primary**: `uv venv` for ultra-fast environment creation and package installation, with native `python -m venv` + `pip` fallback.
|
|
49
|
+
- **Minimal Environment Allowlist**: host secrets (`GEMINI_API_KEY`, cloud tokens, `.env` values) are **never** inherited by the child process. Pass explicit variables via `CodeExecutionRequest(env={...})` or `SubprocessRunner(env_allowlist=[...])`.
|
|
50
|
+
- **Workspace & Resource Guardrails**: scripts execute with `cwd` and temp directories pinned inside the disposable workspace, strict path-traversal & PEP 508 package validation, bounded `stdout`/`stderr` capture (`max_output_bytes`), redacted host paths in tracebacks, and process-tree termination on timeout.
|
|
49
51
|
|
|
50
|
-
### 2.
|
|
52
|
+
### 2. Fail-Closed AST Security Gates
|
|
51
53
|
|
|
52
|
-
The engine parses every snippet with the standard `ast` module and
|
|
54
|
+
The engine parses every snippet (and every LLM-generated patch) with the standard `ast` module and fails closed on:
|
|
53
55
|
|
|
54
56
|
- `SyntaxError`s before execution.
|
|
55
|
-
- Bare `except:` / `except Exception:` / `except BaseException:` handlers.
|
|
56
|
-
-
|
|
57
|
-
-
|
|
57
|
+
- Bare `except:` / `except Exception:` / `except BaseException:` handlers (including tuple handlers).
|
|
58
|
+
- Dangerous builtins & reflection (`eval()`, `exec()`, `compile()`, `__import__()`, `getattr()`, `globals()`, etc.) even when aliased or reassigned.
|
|
59
|
+
- Blocked high-risk modules (`subprocess`, `ctypes`, `importlib`, `pickle`, `socket`, `shutil`, `builtins`, etc.) and dangerous `os`/`sys` APIs (`os.system`, `os.popen`, `os.environ`, `sys.modules`, `sys._getframe`).
|
|
60
|
+
- Reflection dunder traversal (`__subclasses__`, `__builtins__`, `__globals__`, `__class__`, `__bases__`, etc.).
|
|
58
61
|
|
|
59
62
|
### 3. Silent Failure Detection
|
|
60
63
|
|
|
@@ -74,7 +77,7 @@ AST Validation ──► Sandbox Execution ──► Traceback Classification
|
|
|
74
77
|
```
|
|
75
78
|
|
|
76
79
|
- **Local heuristic fallback**: handles `NameError`, `ImportError`, `ModuleNotFoundError` by injecting safe imports or placeholder definitions.
|
|
77
|
-
- **LLM-guided healing**: when an LLM is configured (built-in Gemini
|
|
80
|
+
- **LLM-guided healing**: when an LLM is configured (built-in Gemini 4 by default, or any custom provider via `patch_generator`), it asks the model for a corrected version of the code, validates it with the AST gate, and re-executes the patched snippet.
|
|
78
81
|
|
|
79
82
|
---
|
|
80
83
|
|
|
@@ -106,12 +109,18 @@ pip install -e ".[test,lint,llm,dev]"
|
|
|
106
109
|
### Offline Usage (No API Key)
|
|
107
110
|
|
|
108
111
|
```python
|
|
109
|
-
from codeshield
|
|
112
|
+
from codeshield import SelfHealingEngine
|
|
110
113
|
|
|
114
|
+
# The sandbox is created and destroyed automatically on every ``run`` call.
|
|
111
115
|
engine = SelfHealingEngine(use_llm=False)
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
116
|
+
result, diagnosis = engine.run("print('hello world')")
|
|
117
|
+
print(result.stdout)
|
|
118
|
+
|
|
119
|
+
# Use a ``with`` block to reuse a single sandbox across multiple runs.
|
|
120
|
+
with SelfHealingEngine(use_llm=False) as reusable_engine:
|
|
121
|
+
first, _ = reusable_engine.run("print(1 + 1)")
|
|
122
|
+
second, _ = reusable_engine.run("print(2 + 2)")
|
|
123
|
+
print(first.stdout, second.stdout)
|
|
115
124
|
```
|
|
116
125
|
|
|
117
126
|
### Model-Agnostic Self-Healing (Plug-and-Play)
|
|
@@ -119,13 +128,13 @@ with engine:
|
|
|
119
128
|
CodeShield is not locked into a single LLM. Pass any Python callable as the `patch_generator` to use OpenAI, Anthropic Claude, DeepSeek, Ollama, LiteLLM or your own service:
|
|
120
129
|
|
|
121
130
|
```python
|
|
122
|
-
from codeshield
|
|
131
|
+
from codeshield import SelfHealingEngine
|
|
123
132
|
|
|
124
133
|
|
|
125
134
|
def custom_llm_patcher(code: str, diagnosis) -> str:
|
|
126
|
-
# Compatible with any frontier provider: GPT-5.
|
|
135
|
+
# Compatible with any frontier provider: GPT-5.6, Claude Sonnet 5, DeepSeek V4, Ollama
|
|
127
136
|
response = client.chat.completions.create(
|
|
128
|
-
model="gpt-5.
|
|
137
|
+
model="gpt-5.6-luna", # or "claude-sonnet-5", "deepseek-v4-flash"
|
|
129
138
|
messages=[
|
|
130
139
|
{
|
|
131
140
|
"role": "user",
|
|
@@ -137,20 +146,26 @@ def custom_llm_patcher(code: str, diagnosis) -> str:
|
|
|
137
146
|
|
|
138
147
|
|
|
139
148
|
engine = SelfHealingEngine(patch_generator=custom_llm_patcher)
|
|
149
|
+
|
|
150
|
+
# Broken code -> AST gate -> sandbox execution -> traceback classification ->
|
|
151
|
+
# custom patch -> AST re-validation -> re-execution, all in a single call.
|
|
152
|
+
result, diagnosis = engine.run('print("Result: " + 42)')
|
|
153
|
+
print(result.stdout) # Result: 42
|
|
140
154
|
```
|
|
141
155
|
|
|
142
|
-
### Zero-Config Self-Healing with Gemini
|
|
156
|
+
### Zero-Config Self-Healing with Gemini 4
|
|
143
157
|
|
|
144
158
|
For the built-in zero-config experience, create a `.env` file from `.env.example`:
|
|
145
159
|
|
|
146
160
|
```text
|
|
147
161
|
GEMINI_API_KEY=your_key_here
|
|
148
|
-
GEMINI_MODEL=gemini-
|
|
162
|
+
GEMINI_MODEL=gemini-4-hydrogen
|
|
149
163
|
```
|
|
150
164
|
|
|
151
165
|
```python
|
|
152
166
|
from dotenv import load_dotenv
|
|
153
|
-
|
|
167
|
+
|
|
168
|
+
from codeshield import SelfHealingEngine
|
|
154
169
|
|
|
155
170
|
load_dotenv()
|
|
156
171
|
|
|
@@ -182,12 +197,73 @@ python -m codeshield run script.py --no-llm # force local fallback
|
|
|
182
197
|
```python
|
|
183
198
|
from codeshield import create_code_execution_tool
|
|
184
199
|
|
|
185
|
-
#
|
|
200
|
+
# Standard usage: built-in Gemini healing when configured, local heuristic otherwise
|
|
186
201
|
tools = [create_code_execution_tool()]
|
|
202
|
+
|
|
203
|
+
# Or bring your own model: the patcher is forwarded to the internal engine
|
|
204
|
+
tools = [create_code_execution_tool(patch_generator=custom_llm_patcher)]
|
|
187
205
|
```
|
|
188
206
|
|
|
189
207
|
`create_code_execution_tool()` returns a ready-to-register `execute_python_code(code: str) -> str` function. It runs the provided Python in a self-healing sandbox and returns either the stdout or a structured error report with `error_type` and `stderr`.
|
|
190
208
|
|
|
209
|
+
The callable exposes real type hints and a Google-style docstring, so any SDK that builds a function schema from a plain Python callable can register it directly.
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## Public API
|
|
214
|
+
|
|
215
|
+
Everything is re-exported at the package root, so imports never need internal submodules:
|
|
216
|
+
|
|
217
|
+
```python
|
|
218
|
+
from codeshield import (
|
|
219
|
+
DEFAULT_GEMINI_MODEL,
|
|
220
|
+
ASTSecurityError,
|
|
221
|
+
CodeExecutionRequest,
|
|
222
|
+
ErrorDiagnosis,
|
|
223
|
+
ExecutionResult,
|
|
224
|
+
GeminiPatchGenerator,
|
|
225
|
+
LLMPatchError,
|
|
226
|
+
PatchProposal,
|
|
227
|
+
SandboxError,
|
|
228
|
+
SandboxManager,
|
|
229
|
+
SelfHealingEngine,
|
|
230
|
+
SelfHealingError,
|
|
231
|
+
SubprocessRunner,
|
|
232
|
+
SubprocessRunnerError,
|
|
233
|
+
TracebackClassifier,
|
|
234
|
+
ValidationReport,
|
|
235
|
+
create_code_execution_tool,
|
|
236
|
+
validate_syntax_and_safety,
|
|
237
|
+
)
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
`ASTSecurityError` subclasses `SelfHealingError` and is raised whenever the static AST gate blocks either the original snippet or a generated patch.
|
|
241
|
+
|
|
242
|
+
### Explicit Environment Variables
|
|
243
|
+
|
|
244
|
+
Host environment variables (including API keys loaded from `.env`) are never leaked into executed code. To expose specific variables to a snippet, pass them explicitly:
|
|
245
|
+
|
|
246
|
+
```python
|
|
247
|
+
from codeshield import CodeExecutionRequest, SelfHealingEngine
|
|
248
|
+
|
|
249
|
+
request = CodeExecutionRequest(
|
|
250
|
+
code="import json\nprint(json.dumps({'status': 'ok'}))",
|
|
251
|
+
env={"APP_MODE": "sandbox"},
|
|
252
|
+
)
|
|
253
|
+
with SelfHealingEngine(use_llm=False) as engine:
|
|
254
|
+
result, _ = engine.run(request)
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
---
|
|
258
|
+
|
|
259
|
+
## Security Model & Threat Boundaries
|
|
260
|
+
|
|
261
|
+
CodeShield provides **application-layer defense-in-depth** tailored for LLM-generated data, math, and automation snippets (fail-closed AST checks, env allowlisting, scoped workspace `cwd`, path traversal & pip-flag validation, bounded output capture, host-path redaction, and process-tree termination).
|
|
262
|
+
|
|
263
|
+
> **Threat boundary:** Ephemeral virtualenvs and static AST inspection do **not** provide OS kernel isolation (namespaces, seccomp, cgroups, or network firewalls). For **untrusted or adversarial multi-tenant workloads**, run CodeShield inside a hardened container or microVM (Docker with `--network=none --read-only`, gVisor, or Firecracker).
|
|
264
|
+
|
|
265
|
+
See [SECURITY.md](SECURITY.md) for the full security policy and private vulnerability disclosure instructions.
|
|
266
|
+
|
|
191
267
|
---
|
|
192
268
|
|
|
193
269
|
## Verified Examples
|
|
@@ -197,7 +273,7 @@ The `examples/` folder contains ready-to-run recipes that have been executed and
|
|
|
197
273
|
- `01_basic_sandboxing.py`: isolated execution with timing measurements.
|
|
198
274
|
- `02_security_gatekeeper.py`: AST rejection of unsafe code.
|
|
199
275
|
- `03_llm_healing_workflow.py`: self-healing workflow with an LLM or local fallback.
|
|
200
|
-
- `04_agent_tool_dropin.py`:
|
|
276
|
+
- `04_agent_tool_dropin.py`: dual-phase agentic trace, printing agent thought, tool call, sandbox runtime and final answer for both a legitimate analytics round and a security-defense round where the AST gate blocks a shell escape.
|
|
201
277
|
- `05_custom_llm_openai_compatible.py`: model-agnostic, API-key-free self-healing with a custom `patch_generator`.
|
|
202
278
|
|
|
203
279
|
```bash
|
|
@@ -210,10 +286,10 @@ python examples/05_custom_llm_openai_compatible.py
|
|
|
210
286
|
|
|
211
287
|
## Running Tests & Lint
|
|
212
288
|
|
|
213
|
-
The suite currently has **
|
|
289
|
+
The suite currently has **110 tests** with **>85% code coverage** on `src/codeshield`.
|
|
214
290
|
|
|
215
291
|
```bash
|
|
216
|
-
ruff check src tests examples
|
|
292
|
+
ruff check src tests examples demo.py
|
|
217
293
|
pytest tests -v --cov=src/codeshield
|
|
218
294
|
```
|
|
219
295
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Security Policy
|
|
2
|
+
|
|
3
|
+
## Supported Versions
|
|
4
|
+
|
|
5
|
+
Security fixes are applied to the latest minor release on the `main` branch.
|
|
6
|
+
|
|
7
|
+
| Version | Supported |
|
|
8
|
+
| :--- | :--- |
|
|
9
|
+
| `0.2.x` (latest) | :white_check_mark: |
|
|
10
|
+
| `< 0.2.0` | :x: (upgrade to `>=0.2.0`) |
|
|
11
|
+
|
|
12
|
+
## Security Model & Threat Boundaries
|
|
13
|
+
|
|
14
|
+
CodeShield provides **application-layer defense-in-depth** for executing LLM-generated Python snippets (analytics, data transformation, scripting, and agent tool calls):
|
|
15
|
+
|
|
16
|
+
- **Fail-closed Static AST Gate**: blocks syntax errors, overly broad exception handlers, dangerous builtins (`eval`, `exec`, `compile`, `__import__`, reflection helpers), aliased or variable-rebound calls, restricted modules (`subprocess`, `ctypes`, `importlib`, `pickle`, `socket`, `shutil`, `builtins`, etc.), dangerous `os`/`sys` APIs, and reflection dunder attributes (`__subclasses__`, `__builtins__`, `__globals__`, etc.).
|
|
17
|
+
- **Minimal Environment Allowlist**: subprocesses never inherit the full host `os.environ` (protecting `GEMINI_API_KEY`, cloud credentials, and database secrets). Extra variables must be passed explicitly via `CodeExecutionRequest(env=...)` or `SubprocessRunner(env_allowlist=...)`, while interpreter-hijacking variables (`LD_PRELOAD`, `PYTHONPATH`, `PYTHONSTARTUP`, etc.) are blocked.
|
|
18
|
+
- **Workspace & Path Hardening**: child processes execute with `cwd` locked to the ephemeral sandbox directory, temporary directories redirected inside the workspace, strict validation against path traversal in file/venv names, and strict PEP 508 validation on package specifiers (blocking pip flags, VCS URLs, and local paths).
|
|
19
|
+
- **Resource & Process-Tree Guardrails**: bounded `stdout`/`stderr` capture (`max_output_bytes`) prevents memory exhaustion, `stdin=DEVNULL` prevents interactive hangs, host workspace paths are redacted from `stderr`/tool errors, and timeouts terminate the entire process tree.
|
|
20
|
+
|
|
21
|
+
> **Important boundary:** Python virtualenvs and static AST inspection are **not** a substitute for kernel-level OS isolation. If your deployment runs **untrusted or adversarial multi-tenant code**, run CodeShield inside an OS-level sandbox such as Docker (with `--network=none`, `--read-only`, dropped capabilities, and memory/CPU limits), gVisor, Kata Containers, or Firecracker microVMs.
|
|
22
|
+
|
|
23
|
+
## Reporting a Vulnerability
|
|
24
|
+
|
|
25
|
+
Please **do not** open a public GitHub issue for suspected security vulnerabilities.
|
|
26
|
+
|
|
27
|
+
Instead, report vulnerabilities privately via GitHub Security Advisories:
|
|
28
|
+
|
|
29
|
+
- [Report a vulnerability privately](https://github.com/AlgorithmicMind/codeshield/security/advisories/new)
|
|
30
|
+
|
|
31
|
+
Include a concise description of the issue, affected version, reproduction steps, and potential impact. We aim to acknowledge reports within 72 hours and coordinate a fix before public disclosure.
|
|
@@ -4,13 +4,13 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "codeshield-runtime"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "A secure, isolated, and self-healing Python code execution engine powered by uv and AST analysis."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = { text = "MIT" }
|
|
11
11
|
requires-python = ">=3.10"
|
|
12
12
|
authors = [
|
|
13
|
-
{ name = "
|
|
13
|
+
{ name = "AlgorithmicMind" },
|
|
14
14
|
]
|
|
15
15
|
keywords = ["code", "execution", "sandbox", "self-healing", "ast", "uv"]
|
|
16
16
|
classifiers = [
|
|
@@ -46,6 +46,9 @@ dev = [
|
|
|
46
46
|
"twine>=5.0.0",
|
|
47
47
|
]
|
|
48
48
|
|
|
49
|
+
[project.scripts]
|
|
50
|
+
codeshield = "codeshield.cli:main"
|
|
51
|
+
|
|
49
52
|
[project.urls]
|
|
50
53
|
Homepage = "https://github.com/AlgorithmicMind/codeshield"
|
|
51
54
|
Repository = "https://github.com/AlgorithmicMind/codeshield"
|
|
@@ -59,6 +62,7 @@ include = [
|
|
|
59
62
|
"/src",
|
|
60
63
|
"/tests",
|
|
61
64
|
"/README.md",
|
|
65
|
+
"/SECURITY.md",
|
|
62
66
|
"/LICENSE",
|
|
63
67
|
"/pyproject.toml",
|
|
64
68
|
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""CodeShield.
|
|
2
|
+
|
|
3
|
+
A secure, isolated, and self-healing Python code execution engine.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__version__ = "0.2.0"
|
|
7
|
+
|
|
8
|
+
from codeshield.analyzer import validate_syntax_and_safety
|
|
9
|
+
from codeshield.classifier import TracebackClassifier
|
|
10
|
+
from codeshield.environment import SandboxError, SandboxManager
|
|
11
|
+
from codeshield.loop import (
|
|
12
|
+
DEFAULT_GEMINI_MODEL,
|
|
13
|
+
ASTSecurityError,
|
|
14
|
+
GeminiPatchGenerator,
|
|
15
|
+
LLMPatchError,
|
|
16
|
+
SelfHealingEngine,
|
|
17
|
+
SelfHealingError,
|
|
18
|
+
)
|
|
19
|
+
from codeshield.runner import SubprocessRunner, SubprocessRunnerError
|
|
20
|
+
from codeshield.schemas import (
|
|
21
|
+
CodeExecutionRequest,
|
|
22
|
+
ErrorDiagnosis,
|
|
23
|
+
ExecutionResult,
|
|
24
|
+
PatchProposal,
|
|
25
|
+
ValidationReport,
|
|
26
|
+
)
|
|
27
|
+
from codeshield.tools import create_code_execution_tool
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"ASTSecurityError",
|
|
31
|
+
"CodeExecutionRequest",
|
|
32
|
+
"DEFAULT_GEMINI_MODEL",
|
|
33
|
+
"ErrorDiagnosis",
|
|
34
|
+
"ExecutionResult",
|
|
35
|
+
"GeminiPatchGenerator",
|
|
36
|
+
"LLMPatchError",
|
|
37
|
+
"PatchProposal",
|
|
38
|
+
"SandboxError",
|
|
39
|
+
"SandboxManager",
|
|
40
|
+
"SelfHealingEngine",
|
|
41
|
+
"SelfHealingError",
|
|
42
|
+
"SubprocessRunner",
|
|
43
|
+
"SubprocessRunnerError",
|
|
44
|
+
"TracebackClassifier",
|
|
45
|
+
"ValidationReport",
|
|
46
|
+
"create_code_execution_tool",
|
|
47
|
+
"validate_syntax_and_safety",
|
|
48
|
+
]
|