hennesey 0.1.0__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.
hennesey/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """Hennesey Python SDK.
2
+
3
+ Existing orchestrators treat the sandbox as an external side effect. We own the
4
+ sandbox-to-orchestrator contract. Temporal can't easily absorb this without breaking
5
+ their abstraction model.
6
+ """
7
+ from .adapters import LocalAdapter, MockAdapter, SandboxAdapter, create_adapter
8
+ from .client import (
9
+ BUILTIN_RECONCILERS,
10
+ ApprovalHandle,
11
+ Hennesey,
12
+ Inbox,
13
+ Run,
14
+ TaskQueue,
15
+ Workspace,
16
+ fs_delete_reconciler,
17
+ fs_write_reconciler,
18
+ http_reconciler,
19
+ )
20
+ from .config import load_config
21
+ from .errors import (
22
+ ApprovalDenied,
23
+ ApprovalExpired,
24
+ AuthorityRevoked,
25
+ HenneseyError,
26
+ IdempotencyConflict,
27
+ LeaseConflict,
28
+ LeaseLost,
29
+ LeaseNotClaimable,
30
+ LeaseNotFound,
31
+ OutcomeUnknown,
32
+ ProviderUnavailable,
33
+ ResourceLocked,
34
+ TaskLost,
35
+ Unauthorized,
36
+ ValidationError,
37
+ WriteConflict,
38
+ )
39
+ from .merge import three_way_merge
40
+
41
+ __version__ = "0.1.0"
42
+
43
+ __all__ = [
44
+ "Hennesey", "Run", "Workspace", "TaskQueue", "Inbox", "ApprovalHandle",
45
+ "LocalAdapter", "MockAdapter", "SandboxAdapter", "create_adapter", "load_config", "three_way_merge",
46
+ "BUILTIN_RECONCILERS", "fs_write_reconciler", "fs_delete_reconciler", "http_reconciler",
47
+ "HenneseyError", "LeaseConflict", "LeaseLost", "LeaseNotFound", "LeaseNotClaimable", "WriteConflict", "ResourceLocked",
48
+ "AuthorityRevoked", "ApprovalDenied", "ApprovalExpired", "TaskLost", "IdempotencyConflict", "OutcomeUnknown",
49
+ "ProviderUnavailable", "ValidationError", "Unauthorized",
50
+ ]
hennesey/adapters.py ADDED
@@ -0,0 +1,347 @@
1
+ """Sandbox adapters for the Python SDK.
2
+
3
+ ``LocalAdapter`` uses the same on-disk layout as the TypeScript LocalAdapter, so Python
4
+ and TypeScript workers can share local sandboxes. ``MockAdapter`` is in-memory with
5
+ failure injection. Other providers: implement the ``SandboxAdapter`` protocol.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import secrets
11
+ import shutil
12
+ import subprocess
13
+ import tempfile
14
+ import time
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any, Protocol
18
+
19
+ from .errors import NotFound, ProviderUnavailable
20
+ from .portable import IGNORE, build_snapshot, unpack_snapshot
21
+
22
+
23
+ def _new_id(prefix: str) -> str:
24
+ return f"{prefix}_{int(time.time() * 1000):x}{secrets.token_hex(8)}"
25
+
26
+
27
+ def _now() -> str:
28
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
29
+
30
+
31
+ class SandboxAdapter(Protocol):
32
+ provider: str
33
+
34
+ def create(self, workspace_path: str | None = None, sandbox_id: str | None = None) -> dict[str, Any]: ...
35
+ def pause(self, sandbox_id: str) -> dict[str, Any]: ...
36
+ def resume(self, sandbox_id: str, snap: dict[str, Any]) -> None: ...
37
+ def get_state(self, sandbox_id: str) -> dict[str, Any]: ...
38
+ def is_alive(self, sandbox_id: str) -> bool: ...
39
+ def exec(self, sandbox_id: str, cmd: str, cwd: str | None = None, timeout: float | None = None) -> dict[str, Any]: ...
40
+ def read_file(self, sandbox_id: str, path: str) -> bytes | None: ...
41
+ def write_file(self, sandbox_id: str, path: str, data: bytes | str) -> None: ...
42
+ def delete_file(self, sandbox_id: str, path: str) -> None: ...
43
+ def list_dir(self, sandbox_id: str, path: str) -> list[dict[str, Any]]: ...
44
+ def snapshot_workspace(self, sandbox_id: str, path: str) -> dict[str, Any]: ...
45
+ def restore_workspace(self, sandbox_id: str, path: str, snap: dict[str, Any]) -> None: ...
46
+ def destroy(self, sandbox_id: str) -> None: ...
47
+
48
+
49
+ def _walk(adapter: Any, sid: str, root: str) -> tuple[dict[str, bytes], list[str]]:
50
+ files: dict[str, bytes] = {}
51
+ dirs: list[str] = []
52
+ stack = [root]
53
+ base = root.rstrip("/")
54
+ while stack:
55
+ d = stack.pop()
56
+ for e in adapter.list_dir(sid, d):
57
+ if e["name"] in IGNORE:
58
+ continue
59
+ rel = e["path"][len(base) + 1:]
60
+ if e["type"] == "dir":
61
+ dirs.append(rel)
62
+ stack.append(e["path"])
63
+ else:
64
+ data = adapter.read_file(sid, e["path"])
65
+ if data is not None:
66
+ files[rel] = data
67
+ return files, dirs
68
+
69
+
70
+ def snapshot_via_files(adapter: Any, sid: str, root: str) -> dict[str, Any]:
71
+ files, dirs = _walk(adapter, sid, root)
72
+ return build_snapshot(files, dirs, root, adapter.provider, sid)
73
+
74
+
75
+ def restore_via_files(adapter: Any, sid: str, root: str, snap: dict[str, Any]) -> None:
76
+ files = unpack_snapshot(snap)
77
+ try:
78
+ existing, _ = _walk(adapter, sid, root)
79
+ except Exception:
80
+ existing = {}
81
+ base = root.rstrip("/")
82
+ for rel in existing:
83
+ if rel not in files:
84
+ adapter.delete_file(sid, f"{base}/{rel}")
85
+ for rel, data in files.items():
86
+ adapter.write_file(sid, f"{base}/{rel}", data)
87
+
88
+
89
+ class MockAdapter:
90
+ """In-memory sandboxes with failure injection (kill, provider outage)."""
91
+
92
+ provider = "mock"
93
+
94
+ def __init__(self) -> None:
95
+ self._boxes: dict[str, dict[str, Any]] = {}
96
+ self._snaps: dict[str, dict[str, bytes]] = {}
97
+ self.provider_down = False
98
+
99
+ def kill(self, sandbox_id: str) -> None:
100
+ if sandbox_id in self._boxes:
101
+ self._boxes[sandbox_id]["alive"] = False
102
+
103
+ def _gate(self) -> None:
104
+ if self.provider_down:
105
+ raise ProviderUnavailable("mock provider is down (simulated outage)")
106
+
107
+ def _box(self, sid: str) -> dict[str, Any]:
108
+ self._gate()
109
+ b = self._boxes.get(sid)
110
+ if not b:
111
+ raise NotFound(f"Sandbox {sid} not found")
112
+ if not b["alive"]:
113
+ raise ProviderUnavailable(f"Sandbox {sid} is dead")
114
+ return b
115
+
116
+ @staticmethod
117
+ def _norm(p: str) -> str:
118
+ parts: list[str] = []
119
+ for seg in p.replace("\\", "/").split("/"):
120
+ if seg in ("", "."):
121
+ continue
122
+ if seg == "..":
123
+ if parts:
124
+ parts.pop()
125
+ else:
126
+ parts.append(seg)
127
+ return "/" + "/".join(parts)
128
+
129
+ def create(self, workspace_path: str | None = None, sandbox_id: str | None = None) -> dict[str, Any]:
130
+ self._gate()
131
+ sid = sandbox_id or _new_id("sbx")
132
+ ws = workspace_path or "/workspace"
133
+ self._boxes[sid] = {"files": {}, "alive": True, "workspace": ws}
134
+ return {"id": sid, "provider": "mock", "workspace_path": ws}
135
+
136
+ def pause(self, sandbox_id: str) -> dict[str, Any]:
137
+ b = self._box(sandbox_id)
138
+ ref = _new_id("msnap")
139
+ self._snaps[ref] = dict(b["files"])
140
+ return {"provider": "mock", "ref": ref, "created_at": _now(), "sandbox_id": sandbox_id}
141
+
142
+ def resume(self, sandbox_id: str, snap: dict[str, Any]) -> None:
143
+ self._gate()
144
+ self._boxes[sandbox_id] = {"files": dict(self._snaps[snap["ref"]]), "alive": True, "workspace": "/workspace"}
145
+
146
+ def get_state(self, sandbox_id: str) -> dict[str, Any]:
147
+ self._box(sandbox_id)
148
+ return {"open_files": [], "running_pids": [], "browser_sessions": []}
149
+
150
+ def is_alive(self, sandbox_id: str) -> bool:
151
+ if self.provider_down:
152
+ return False
153
+ b = self._boxes.get(sandbox_id)
154
+ return bool(b and b["alive"])
155
+
156
+ def exec(self, sandbox_id: str, cmd: str, cwd: str | None = None, timeout: float | None = None) -> dict[str, Any]:
157
+ self._box(sandbox_id)
158
+ head, _, rest = cmd.strip().partition(" ")
159
+ if head == "echo":
160
+ return {"exit_code": 0, "stdout": rest.strip("'\"") + "\n", "stderr": ""}
161
+ if head in ("true", "false"):
162
+ return {"exit_code": 0 if head == "true" else 1, "stdout": "", "stderr": ""}
163
+ return {"exit_code": 127, "stdout": "", "stderr": f"mock: command not found: {head}\n"}
164
+
165
+ def read_file(self, sandbox_id: str, path: str) -> bytes | None:
166
+ return self._box(sandbox_id)["files"].get(self._norm(path))
167
+
168
+ def write_file(self, sandbox_id: str, path: str, data: bytes | str) -> None:
169
+ self._box(sandbox_id)["files"][self._norm(path)] = data.encode() if isinstance(data, str) else bytes(data)
170
+
171
+ def delete_file(self, sandbox_id: str, path: str) -> None:
172
+ self._box(sandbox_id)["files"].pop(self._norm(path), None)
173
+
174
+ def list_dir(self, sandbox_id: str, path: str) -> list[dict[str, Any]]:
175
+ files = self._box(sandbox_id)["files"]
176
+ d = self._norm(path)
177
+ prefix = "/" if d == "/" else d + "/"
178
+ seen: dict[str, dict[str, Any]] = {}
179
+ for p, data in files.items():
180
+ if not p.startswith(prefix):
181
+ continue
182
+ first, _, more = p[len(prefix):].partition("/")
183
+ if more:
184
+ seen[first] = {"name": first, "path": prefix + first, "type": "dir"}
185
+ elif first not in seen:
186
+ seen[first] = {"name": first, "path": prefix + first, "type": "file", "size": len(data)}
187
+ return sorted(seen.values(), key=lambda e: e["name"])
188
+
189
+ def snapshot_workspace(self, sandbox_id: str, path: str) -> dict[str, Any]:
190
+ return snapshot_via_files(self, sandbox_id, self._norm(path))
191
+
192
+ def restore_workspace(self, sandbox_id: str, path: str, snap: dict[str, Any]) -> None:
193
+ restore_via_files(self, sandbox_id, self._norm(path), snap)
194
+
195
+ def destroy(self, sandbox_id: str) -> None:
196
+ self._gate()
197
+ self._boxes.pop(sandbox_id, None)
198
+
199
+
200
+ class LocalAdapter:
201
+ """Each sandbox is a directory; commands run as child processes. Not an isolation boundary."""
202
+
203
+ provider = "local"
204
+
205
+ def __init__(self, root: str | None = None) -> None:
206
+ self.root = Path(root or Path(tempfile.gettempdir()) / "hennesey-sandboxes").resolve()
207
+ self.root.mkdir(parents=True, exist_ok=True)
208
+
209
+ def _dir(self, sid: str) -> Path:
210
+ if not sid or any(c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" for c in sid):
211
+ raise NotFound(f"Invalid sandbox id {sid}")
212
+ return self.root / sid
213
+
214
+ def _meta_path(self, sid: str) -> Path:
215
+ return self._dir(sid) / ".hennesey-sandbox.json"
216
+
217
+ def _meta(self, sid: str) -> dict[str, Any] | None:
218
+ try:
219
+ return json.loads(self._meta_path(sid).read_text())
220
+ except (OSError, ValueError):
221
+ return None
222
+
223
+ def _write_meta(self, m: dict[str, Any]) -> None:
224
+ self._meta_path(m["id"]).write_text(json.dumps(m, indent=2))
225
+
226
+ def _alive_meta(self, sid: str) -> dict[str, Any]:
227
+ m = self._meta(sid)
228
+ if not m:
229
+ raise NotFound(f"Sandbox {sid} not found under {self.root}")
230
+ if m.get("state") == "dead":
231
+ raise ProviderUnavailable(f"Sandbox {sid} is dead")
232
+ return m
233
+
234
+ def fs_path(self, sid: str, p: str) -> Path:
235
+ base = self._dir(sid).resolve()
236
+ full = (base / p.lstrip("/")).resolve()
237
+ if full != base and base not in full.parents:
238
+ raise NotFound(f"Path {p} escapes sandbox {sid}")
239
+ return full
240
+
241
+ def kill(self, sandbox_id: str) -> None:
242
+ m = self._meta(sandbox_id)
243
+ if m:
244
+ m["state"] = "dead"
245
+ self._write_meta(m)
246
+
247
+ def create(self, workspace_path: str | None = None, sandbox_id: str | None = None) -> dict[str, Any]:
248
+ sid = sandbox_id or _new_id("sbx")
249
+ ws = workspace_path or "/workspace"
250
+ self.fs_path(sid, ws).mkdir(parents=True, exist_ok=True)
251
+ self._write_meta({"id": sid, "state": "running", "workspacePath": ws, "pids": [], "created_at": _now()})
252
+ return {"id": sid, "provider": "local", "workspace_path": ws}
253
+
254
+ def pause(self, sandbox_id: str) -> dict[str, Any]:
255
+ m = self._alive_meta(sandbox_id)
256
+ snap = self.snapshot_workspace(sandbox_id, m.get("workspacePath", "/workspace"))
257
+ ref = _new_id("lsnap")
258
+ d = self.root / ".snapshots"
259
+ d.mkdir(exist_ok=True)
260
+ (d / f"{ref}.tar.gz").write_bytes(snap["data"])
261
+ (d / f"{ref}.json").write_text(json.dumps(snap["manifest"]))
262
+ m["state"] = "paused"
263
+ self._write_meta(m)
264
+ return {"provider": "local", "ref": ref, "created_at": _now(), "sandbox_id": sandbox_id}
265
+
266
+ def resume(self, sandbox_id: str, snap: dict[str, Any]) -> None:
267
+ d = self.root / ".snapshots"
268
+ m = self._meta(sandbox_id)
269
+ if m is None:
270
+ self.create(sandbox_id=sandbox_id)
271
+ m = self._meta(sandbox_id) or {}
272
+ m["state"] = "running"
273
+ self._write_meta(m)
274
+ self.restore_workspace(sandbox_id, m.get("workspacePath", "/workspace"), {
275
+ "manifest": json.loads((d / f"{snap['ref']}.json").read_text()),
276
+ "data": (d / f"{snap['ref']}.tar.gz").read_bytes(),
277
+ })
278
+
279
+ def get_state(self, sandbox_id: str) -> dict[str, Any]:
280
+ self._alive_meta(sandbox_id)
281
+ return {"open_files": [], "running_pids": [], "browser_sessions": []}
282
+
283
+ def is_alive(self, sandbox_id: str) -> bool:
284
+ m = self._meta(sandbox_id)
285
+ return bool(m and m.get("state") == "running" and self._dir(sandbox_id).exists())
286
+
287
+ def exec(self, sandbox_id: str, cmd: str, cwd: str | None = None, timeout: float | None = None) -> dict[str, Any]:
288
+ m = self._alive_meta(sandbox_id)
289
+ workdir = self.fs_path(sandbox_id, cwd or m.get("workspacePath", "/workspace"))
290
+ workdir.mkdir(parents=True, exist_ok=True)
291
+ r = subprocess.run(cmd, shell=True, cwd=workdir, capture_output=True, text=True, timeout=timeout)
292
+ return {"exit_code": r.returncode, "stdout": r.stdout, "stderr": r.stderr}
293
+
294
+ def read_file(self, sandbox_id: str, path: str) -> bytes | None:
295
+ self._alive_meta(sandbox_id)
296
+ p = self.fs_path(sandbox_id, path)
297
+ return p.read_bytes() if p.is_file() else None
298
+
299
+ def write_file(self, sandbox_id: str, path: str, data: bytes | str) -> None:
300
+ self._alive_meta(sandbox_id)
301
+ p = self.fs_path(sandbox_id, path)
302
+ p.parent.mkdir(parents=True, exist_ok=True)
303
+ p.write_bytes(data.encode() if isinstance(data, str) else bytes(data))
304
+
305
+ def delete_file(self, sandbox_id: str, path: str) -> None:
306
+ self._alive_meta(sandbox_id)
307
+ p = self.fs_path(sandbox_id, path)
308
+ if p.is_file():
309
+ p.unlink()
310
+
311
+ def list_dir(self, sandbox_id: str, path: str) -> list[dict[str, Any]]:
312
+ self._alive_meta(sandbox_id)
313
+ p = self.fs_path(sandbox_id, path)
314
+ if not p.is_dir():
315
+ return []
316
+ base = path.rstrip("/")
317
+ out = []
318
+ for child in sorted(p.iterdir(), key=lambda c: c.name):
319
+ out.append({"name": child.name, "path": f"{base}/{child.name}", "type": "dir" if child.is_dir() else "file"})
320
+ return out
321
+
322
+ def snapshot_workspace(self, sandbox_id: str, path: str) -> dict[str, Any]:
323
+ self._alive_meta(sandbox_id)
324
+ return snapshot_via_files(self, sandbox_id, path)
325
+
326
+ def restore_workspace(self, sandbox_id: str, path: str, snap: dict[str, Any]) -> None:
327
+ self._alive_meta(sandbox_id)
328
+ self.fs_path(sandbox_id, path).mkdir(parents=True, exist_ok=True)
329
+ restore_via_files(self, sandbox_id, path, snap)
330
+
331
+ def destroy(self, sandbox_id: str) -> None:
332
+ shutil.rmtree(self._dir(sandbox_id), ignore_errors=True)
333
+
334
+
335
+ def create_adapter(provider: str, config: dict[str, Any] | None = None) -> Any:
336
+ config = config or {}
337
+ if provider == "mock":
338
+ return MockAdapter()
339
+ if provider == "local":
340
+ return LocalAdapter(root=config.get("root"))
341
+ raise ProviderUnavailable(
342
+ f"The Python SDK has built-in adapters for 'local' and 'mock'. For '{provider}', pass your own adapter "
343
+ "object implementing hennesey.adapters.SandboxAdapter (see docs)."
344
+ )
345
+
346
+
347
+ __all__ = ["SandboxAdapter", "MockAdapter", "LocalAdapter", "create_adapter", "snapshot_via_files", "restore_via_files"]