agent-jail-cli 0.1.6__py3-none-any.whl

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.
agent_jail/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """agent-jail: Zero-overhead, OS-level sandboxing for autonomous AI agents."""
2
+
3
+ __version__ = "0.1.6"
agent_jail/cli.py ADDED
@@ -0,0 +1,215 @@
1
+ """Command-line interface for agent-jail and aj."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ import resource
8
+ import shutil
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ from typing import NoReturn
14
+
15
+ from agent_jail import __version__
16
+ from agent_jail.config import init_config, load_config
17
+ from agent_jail.runners import get_runner
18
+
19
+
20
+ def print_help(prog: str) -> None:
21
+ print(f"""agent-jail (v{__version__}) - Kernel-enforced sandboxing for AI agents
22
+
23
+ Usage:
24
+ {prog} <command> [args...] Run any agent harness, CLI tool, or script sandboxed
25
+ {prog} claude / codex / pi Run any coding agent CLI inside the sandbox
26
+ {prog} python agent.py Run custom Python agent loop (LangChain, DeepAgents, etc.)
27
+ {prog} bash Launch an interactive sandboxed shell
28
+ {prog} Launch an interactive sandboxed shell (default)
29
+
30
+ Options:
31
+ --init Create default aj-conf.yaml in current project
32
+ -h, --help Show this help message and exit
33
+ -v, --version Show version number
34
+
35
+ Environment:
36
+ AGENT_JAIL_CMD Override command string (executed via bash -c)
37
+ HTTP_PROXY / HTTPS_PROXY Automatically directed to local dynamic proxy
38
+ """)
39
+
40
+
41
+ def set_resource_limits() -> None:
42
+ """Set process and file descriptor caps to prevent fork bombs and descriptor leaks."""
43
+ # On macOS, RLIMIT_NPROC is enforced per-UID across the whole user session
44
+ # rather than per-process, which causes EAGAIN if the user already has >512 processes.
45
+ if sys.platform != "darwin":
46
+ try:
47
+ if hasattr(resource, "RLIMIT_NPROC"):
48
+ resource.setrlimit(resource.RLIMIT_NPROC, (512, 512))
49
+ except Exception:
50
+ pass
51
+
52
+ try:
53
+ if hasattr(resource, "RLIMIT_NOFILE"):
54
+ soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
55
+ target = min(2048, hard) if hard > 0 else 2048
56
+ resource.setrlimit(resource.RLIMIT_NOFILE, (target, hard))
57
+ except Exception:
58
+ pass
59
+
60
+
61
+ def start_proxy(allowlist: Path) -> tuple[subprocess.Popen, int]:
62
+ """Start the unjailed dynamic forward proxy on 127.0.0.1:0 and read its assigned port."""
63
+ proxy_proc = subprocess.Popen(
64
+ [
65
+ sys.executable,
66
+ "-m",
67
+ "agent_jail.proxy",
68
+ "--allowlist",
69
+ str(allowlist),
70
+ "--port",
71
+ "0",
72
+ ],
73
+ stdout=subprocess.PIPE,
74
+ stderr=subprocess.PIPE,
75
+ text=True,
76
+ )
77
+
78
+ if not proxy_proc.stdout:
79
+ proxy_proc.kill()
80
+ raise RuntimeError("Failed to open pipe for forward proxy process.")
81
+
82
+ line = proxy_proc.stdout.readline().strip()
83
+ if not line.startswith("PORT="):
84
+ proxy_proc.kill()
85
+ raise RuntimeError(f"Unexpected proxy initialization response: {line}")
86
+
87
+ try:
88
+ port = int(line[len("PORT=") :])
89
+ except ValueError:
90
+ proxy_proc.kill()
91
+ raise RuntimeError(f"Invalid proxy port announced: {line}")
92
+
93
+ return proxy_proc, port
94
+
95
+
96
+ def main() -> NoReturn:
97
+ raw_args = sys.argv[1:]
98
+ prog = Path(sys.argv[0]).name
99
+
100
+ if raw_args and raw_args[0] in ("-h", "--help"):
101
+ print_help(prog)
102
+ sys.exit(0)
103
+
104
+ if raw_args and raw_args[0] in ("-v", "--version"):
105
+ print(f"agent-jail {__version__}")
106
+ sys.exit(0)
107
+
108
+ # 1. Project Directory Guard: Prevent running directly in $HOME or parent of it
109
+ project = Path.cwd().resolve()
110
+ home = Path.home().resolve()
111
+
112
+ if project == home or project in home.parents:
113
+ sys.stderr.write(
114
+ f"agent-jail: refusing to run with project = $HOME or parent of it ({project})\n"
115
+ )
116
+ sys.exit(1)
117
+
118
+ # Handle --init
119
+ if raw_args and raw_args[0] == "--init":
120
+ conf_file = init_config(project, home)
121
+ sys.stderr.write(f"agent-jail: 📝 Initialized {conf_file.name} in {project}\n")
122
+ sys.exit(0)
123
+
124
+ # 2. Check platform prerequisites
125
+ runner = get_runner()
126
+ try:
127
+ runner.check_prerequisites()
128
+ except Exception as e:
129
+ sys.stderr.write(f"agent-jail error: {e}\n")
130
+ sys.exit(1)
131
+
132
+ # 3. Load or initialize project configuration
133
+ config, conf_path, was_created = load_config(project, home)
134
+ if was_created:
135
+ sys.stderr.write(f"agent-jail: 📝 Created default {conf_path.name} in project\n")
136
+
137
+ # 4. Ephemeral Temp Directory
138
+ run_tmp = Path(tempfile.mkdtemp(prefix="agent_jail_tmp_")).resolve()
139
+
140
+ # Write domain allowlist to temp file for proxy
141
+ allowlist_file = run_tmp / "allowed_domains.txt"
142
+ allowlist_file.write_text("\n".join(config.allowed_domains) + "\n", encoding="utf-8")
143
+
144
+ # 5. Start unjailed forward proxy
145
+ try:
146
+ proxy_proc, proxy_port = start_proxy(allowlist_file)
147
+ except Exception as e:
148
+ shutil.rmtree(run_tmp, ignore_errors=True)
149
+ sys.stderr.write(f"agent-jail: failed to initialize proxy: {e}\n")
150
+ sys.exit(1)
151
+
152
+ # 6. Apply resource limits before executing child
153
+ set_resource_limits()
154
+
155
+ # 7. Determine command to execute
156
+ if "AGENT_JAIL_CMD" in os.environ:
157
+ cmd = ["/bin/bash", "-c", os.environ["AGENT_JAIL_CMD"]]
158
+ elif raw_args:
159
+ cmd = raw_args
160
+ else:
161
+ # Default to interactive shell
162
+ cmd = [os.environ.get("SHELL", "/bin/bash")]
163
+
164
+ sys.stderr.write(
165
+ f"agent-jail: 🔒 {project} | 🌐 proxy:127.0.0.1:{proxy_port} ({conf_path.name})\n"
166
+ )
167
+ sys.stderr.flush()
168
+
169
+ # 8. Build command & environment
170
+ exec_cmd = runner.build_command(
171
+ project=project,
172
+ home=home,
173
+ proxy_port=proxy_port,
174
+ run_tmp=run_tmp,
175
+ cmd=cmd,
176
+ config=config,
177
+ )
178
+ safe_env = runner.build_safe_env(proxy_port, run_tmp, config=config)
179
+
180
+ exit_code = 0
181
+ try:
182
+ # Launch child process with scrubbed environment
183
+ child = subprocess.Popen(exec_cmd, env=safe_env)
184
+
185
+ # Forward signals to child process
186
+ def handle_signal(sig: int, frame: object) -> None:
187
+ try:
188
+ child.send_signal(sig)
189
+ except Exception:
190
+ pass
191
+
192
+ signal.signal(signal.SIGINT, handle_signal)
193
+ signal.signal(signal.SIGTERM, handle_signal)
194
+
195
+ exit_code = child.wait()
196
+ except KeyboardInterrupt:
197
+ exit_code = 130
198
+ except Exception as e:
199
+ sys.stderr.write(f"agent-jail execution error: {e}\n")
200
+ exit_code = 1
201
+ finally:
202
+ # Cleanup proxy and ephemeral directory
203
+ try:
204
+ proxy_proc.terminate()
205
+ proxy_proc.wait(timeout=2.0)
206
+ except Exception:
207
+ proxy_proc.kill()
208
+
209
+ shutil.rmtree(run_tmp, ignore_errors=True)
210
+
211
+ sys.exit(exit_code)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ main()
agent_jail/config.py ADDED
@@ -0,0 +1,247 @@
1
+ """Configuration management for agent-jail using aj-conf.yaml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ import shutil
8
+ import sys
9
+ from typing import Any
10
+ import yaml
11
+
12
+ if sys.version_info >= (3, 11):
13
+ import tomllib
14
+ else:
15
+ try:
16
+ import tomli as tomllib # type: ignore
17
+ except ImportError:
18
+ tomllib = None # type: ignore
19
+
20
+
21
+ DEFAULT_CONFIG_TEMPLATE = """# aj-conf.yaml - Configuration for agent-jail (aj)
22
+
23
+ network:
24
+ # Outbound domains, wildcards (*.domain.com), or specific host:port endpoints
25
+ allowed_domains:
26
+ - github.com
27
+ - "*.github.com"
28
+ - githubusercontent.com
29
+ - "*.githubusercontent.com"
30
+ - pypi.org
31
+ - "*.pypi.org"
32
+ - pythonhosted.org
33
+ - "*.pythonhosted.org"
34
+ - huggingface.co
35
+ - "*.huggingface.co"
36
+ - registry.npmjs.org
37
+ # Cloud LLM APIs (uncomment as needed):
38
+ # - api.openai.com
39
+ # - api.anthropic.com
40
+ # - generativelanguage.googleapis.com
41
+ # - openrouter.ai
42
+ # Local LLM servers (standard ports):
43
+ # - 127.0.0.1:11434 # Ollama
44
+ # - 127.0.0.1:8080 # llama.cpp (llama-server)
45
+ # - 127.0.0.1:4000 # LiteLLM Proxy
46
+ # - 127.0.0.1:1234 # LM Studio
47
+ # - 127.0.0.1:8000 # vLLM / Local FastAPI
48
+
49
+ filesystem:
50
+ # Directories permitted for read access.
51
+ # Default: ["."] grants read access to the entire project directory.
52
+ # Restrict to specific subfolders (e.g. ["src", ".venv"]) for granular reads.
53
+ read:
54
+ - .
55
+
56
+ # Specific files or directories to hide completely (deny read).
57
+ # Useful when read: ["."] is enabled but you want to protect secrets.
58
+ hide:
59
+ # - .env
60
+ # - secrets
61
+
62
+ # Directories permitted for write access.
63
+ # Default: ["."] grants write access to the project directory.
64
+ # Restrict to specific subfolders (e.g. ["output", ".cache"]) for granular access,
65
+ # or leave empty ([]) to make the entire project strictly read-only.
66
+ write:
67
+ - .
68
+
69
+ env:
70
+ # Host environment variables to pass into the sandbox
71
+ passthrough:
72
+ # - OPENAI_API_KEY
73
+ # - ANTHROPIC_API_KEY
74
+ # - GEMINI_API_KEY
75
+ """
76
+
77
+
78
+ @dataclass
79
+ class JailConfig:
80
+ """Parsed agent-jail project configuration."""
81
+
82
+ allowed_domains: list[str] = field(default_factory=list)
83
+ allowed_ports: list[int] = field(default_factory=list)
84
+ fs_read: list[Path] = field(default_factory=list)
85
+ fs_hide: list[Path] = field(default_factory=list)
86
+ fs_write: list[Path] = field(default_factory=list)
87
+ env_passthrough: list[str] = field(default_factory=list)
88
+
89
+
90
+ def init_config(project: Path, home: Path | None = None) -> Path:
91
+ """Create aj-conf.yaml in the project directory.
92
+
93
+ If ~/.aj/default_conf.yaml exists, copies it; otherwise writes the default template.
94
+ """
95
+ conf_path = project / "aj-conf.yaml"
96
+ if conf_path.exists():
97
+ return conf_path
98
+
99
+ if home is None:
100
+ home = Path.home().resolve()
101
+
102
+ # Check for user template in ~/.aj/default_conf.yaml or .yml
103
+ user_defaults = [
104
+ home / ".aj" / "default_conf.yaml",
105
+ home / ".aj" / "default_conf.yml",
106
+ ]
107
+ for user_def in user_defaults:
108
+ if user_def.is_file():
109
+ shutil.copyfile(user_def, conf_path)
110
+ return conf_path
111
+
112
+ # Fallback to default template
113
+ conf_path.write_text(DEFAULT_CONFIG_TEMPLATE, encoding="utf-8")
114
+ return conf_path
115
+
116
+
117
+ def resolve_fs_path(entry: str | Path, project: Path | None = None) -> Path:
118
+ """Resolve a filesystem path entry, supporting relative paths and $PROJECT."""
119
+ p_str = str(entry).strip()
120
+ if project is not None:
121
+ p_str = p_str.replace("${PROJECT}", str(project)).replace("$PROJECT", str(project))
122
+ path = Path(p_str).expanduser()
123
+ if not path.is_absolute():
124
+ if project is not None:
125
+ if p_str in (".", "./"):
126
+ return project.resolve()
127
+ return (project / path).resolve()
128
+ return path.resolve()
129
+ return path.resolve()
130
+
131
+
132
+ def load_config(project: Path, home: Path) -> tuple[JailConfig, Path, bool]:
133
+ """Load project configuration. Returns (JailConfig, path, was_created).
134
+
135
+ Checks for:
136
+ 1. aj-conf.yaml
137
+ 2. aj-conf.yml
138
+ 3. aj-conf.toml (fallback)
139
+ 4. Legacy .allowed_domains
140
+ 5. Auto-creates aj-conf.yaml (copying ~/.aj/default_conf.yaml if present)
141
+ """
142
+ for yaml_name in ["aj-conf.yaml", "aj-conf.yml"]:
143
+ yaml_path = project / yaml_name
144
+ if yaml_path.is_file():
145
+ raw = yaml.safe_load(yaml_path.read_text(encoding="utf-8")) or {}
146
+ return _build_config(raw, project=project), yaml_path, False
147
+
148
+ toml_path = project / "aj-conf.toml"
149
+ if toml_path.is_file() and tomllib is not None:
150
+ raw = tomllib.loads(toml_path.read_text(encoding="utf-8"))
151
+ return _build_config(raw, project=project), toml_path, False
152
+
153
+ # Check for legacy .allowed_domains
154
+ for legacy_name in [".allowed_domains", ".allowed_domains.txt"]:
155
+ legacy_path = project / legacy_name
156
+ if legacy_path.is_file():
157
+ domains = []
158
+ for line in legacy_path.read_text(encoding="utf-8").splitlines():
159
+ line = line.strip()
160
+ if line and not line.startswith("#"):
161
+ domains.append(line)
162
+ return (
163
+ _build_config({"network": {"allowed_domains": domains}}, project=project),
164
+ legacy_path,
165
+ False,
166
+ )
167
+
168
+ # Auto-initialize aj-conf.yaml in project
169
+ created_path = init_config(project, home)
170
+ raw = yaml.safe_load(created_path.read_text(encoding="utf-8")) or {}
171
+ return _build_config(raw, project=project), created_path, True
172
+
173
+
174
+ def _build_config(raw: dict[str, Any], project: Path | None = None) -> JailConfig:
175
+ network = raw.get("network") or {}
176
+ filesystem = raw.get("filesystem") or {}
177
+ env_cfg = raw.get("env") or {}
178
+
179
+ # Extract allowed domains
180
+ domains_raw = network.get("allowed_domains") or []
181
+ domains = [str(d).strip() for d in domains_raw if str(d).strip()]
182
+
183
+ # Automatically derive localhost ports if specified in allowed_domains (e.g. 127.0.0.1:11434 or localhost:8080)
184
+ ports: list[int] = []
185
+ for entry in domains:
186
+ if ":" in entry:
187
+ host_part, port_str = entry.split(":", 1)
188
+ host_clean = host_part.lower().strip()
189
+ if host_clean in ("localhost", "127.0.0.1", "0.0.0.0", "::1"):
190
+ try:
191
+ ports.append(int(port_str.strip()))
192
+ except ValueError:
193
+ pass
194
+
195
+ # Support explicit allowed_ports if also provided
196
+ ports_raw = network.get("allowed_ports") or []
197
+ for p in ports_raw:
198
+ try:
199
+ p_int = int(p)
200
+ if p_int not in ports:
201
+ ports.append(p_int)
202
+ except (ValueError, TypeError):
203
+ pass
204
+
205
+ # Read paths:
206
+ # If "read" is explicitly present in filesystem: parse the list (even if empty [])
207
+ # If "read" is not present (e.g. legacy configs): default to [project]
208
+ if "read" in filesystem:
209
+ read_raw = filesystem.get("read") or []
210
+ read_paths = [
211
+ resolve_fs_path(p, project)
212
+ for p in read_raw
213
+ if str(p).strip()
214
+ ]
215
+ else:
216
+ read_paths = [project] if project is not None else []
217
+
218
+ # Hide paths: specific files or directories to deny read access to
219
+ hide_raw = filesystem.get("hide") or []
220
+ hide_paths = [
221
+ resolve_fs_path(p, project)
222
+ for p in hide_raw
223
+ if str(p).strip()
224
+ ]
225
+
226
+ # Write paths
227
+ write_raw = filesystem.get("write") or []
228
+ write_paths = [
229
+ resolve_fs_path(p, project)
230
+ for p in write_raw
231
+ if str(p).strip()
232
+ ]
233
+
234
+ # Env passthrough
235
+ pass_raw = env_cfg.get("passthrough") or []
236
+ passthrough = [
237
+ str(e).strip() for e in pass_raw if str(e).strip()
238
+ ]
239
+
240
+ return JailConfig(
241
+ allowed_domains=domains,
242
+ allowed_ports=ports,
243
+ fs_read=read_paths,
244
+ fs_hide=hide_paths,
245
+ fs_write=write_paths,
246
+ env_passthrough=passthrough,
247
+ )