kosa8 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.
kosa8/__init__.py ADDED
@@ -0,0 +1,69 @@
1
+ """kosa8: microVM sandboxes for AI agents, with checkpoint, rewind, fork and explore.
2
+
3
+ The Python counterpart of ``@kosa8/sdk``. No dependencies: it speaks HTTP to the
4
+ local kosa8 daemon over its unix socket, or to a remote worker (``KOSA8_HOST``).
5
+
6
+ >>> from kosa8 import Kosa8Client
7
+ >>> k = Kosa8Client()
8
+ >>> sb = k.sandbox(k.create_sandbox(name="demo", egress="deny")["sandbox"]["id"])
9
+ >>> sb.pull("alpine:latest")
10
+ >>> sb.run("alpine:latest", ["echo", "hi"]).stdout
11
+ 'hi\\n'
12
+ """
13
+
14
+ from .checkpoints import (
15
+ MAX_CHECKPOINTS_PER_SANDBOX,
16
+ CheckpointBook,
17
+ FileCheckpointStore,
18
+ MemoryCheckpointStore,
19
+ )
20
+ from .client import ExecResult, ExploreBranch, ExploreResult, Kosa8Client, Sandbox
21
+ from .errors import (
22
+ Kosa8ApiError,
23
+ Kosa8ApprovalRequiredError,
24
+ Kosa8AuthError,
25
+ Kosa8BadRequestError,
26
+ Kosa8CheckpointError,
27
+ Kosa8ConflictError,
28
+ Kosa8ConnectionError,
29
+ Kosa8Error,
30
+ Kosa8NotFoundError,
31
+ Kosa8PolicyError,
32
+ Kosa8StreamError,
33
+ Kosa8TimeoutError,
34
+ Kosa8UnsupportedError,
35
+ error_from_response,
36
+ )
37
+ from .transport import Transport, default_socket_path, resolve_endpoint
38
+
39
+ __version__ = "0.1.0"
40
+
41
+ __all__ = [
42
+ "Kosa8Client",
43
+ "Sandbox",
44
+ "ExecResult",
45
+ "ExploreBranch",
46
+ "ExploreResult",
47
+ "Transport",
48
+ "default_socket_path",
49
+ "resolve_endpoint",
50
+ "CheckpointBook",
51
+ "FileCheckpointStore",
52
+ "MemoryCheckpointStore",
53
+ "MAX_CHECKPOINTS_PER_SANDBOX",
54
+ "Kosa8Error",
55
+ "Kosa8ConnectionError",
56
+ "Kosa8ApiError",
57
+ "Kosa8BadRequestError",
58
+ "Kosa8AuthError",
59
+ "Kosa8PolicyError",
60
+ "Kosa8ApprovalRequiredError",
61
+ "Kosa8NotFoundError",
62
+ "Kosa8ConflictError",
63
+ "Kosa8UnsupportedError",
64
+ "Kosa8StreamError",
65
+ "Kosa8CheckpointError",
66
+ "Kosa8TimeoutError",
67
+ "error_from_response",
68
+ "__version__",
69
+ ]
kosa8/checkpoints.py ADDED
@@ -0,0 +1,195 @@
1
+ """Checkpoints: client-side bookkeeping over daemon snapshots, exactly as pkg/checkpoint.
2
+
3
+ A checkpoint is a snapshot with the id ``<sandbox>-ckpt-<n>``; an ordered stack
4
+ of them per sandbox records labels and order. The daemon has no checkpoint
5
+ endpoint. The default store is the CLI's own ``~/.kosa8/checkpoints.json``,
6
+ locked with the same ``flock`` on ``checkpoints.json.lock`` the Go tools take,
7
+ so checkpoints taken here are seen by ``kosa8 rewind`` and the other way round.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import copy
13
+ import json
14
+ import os
15
+ import re
16
+ import threading
17
+ from datetime import datetime, timezone
18
+ from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar
19
+
20
+ from .errors import Kosa8CheckpointError
21
+
22
+ #: How many checkpoints are kept per sandbox; the oldest is evicted (pkg/checkpoint MaxPerSandbox).
23
+ MAX_CHECKPOINTS_PER_SANDBOX = 10
24
+
25
+ T = TypeVar("T")
26
+ StoreData = Dict[str, List[Dict[str, Any]]]
27
+
28
+
29
+ def validate_sandbox_name(name: str) -> None:
30
+ """Reject a name that could escape the store (pkg/checkpoint validSandbox)."""
31
+ if name in ("", ".", "..") or "/" in name or "\\" in name or name.startswith("."):
32
+ raise Kosa8CheckpointError(f"invalid sandbox name {json.dumps(name)}")
33
+
34
+
35
+ class MemoryCheckpointStore:
36
+ """Keeps stacks in memory only; nothing is shared with the kosa8 CLI."""
37
+
38
+ def __init__(self) -> None:
39
+ self._data: StoreData = {}
40
+ self._mu = threading.Lock()
41
+
42
+ def load(self) -> StoreData:
43
+ with self._mu:
44
+ return copy.deepcopy(self._data)
45
+
46
+ def update(self, fn: Callable[[StoreData], T]) -> T:
47
+ with self._mu:
48
+ data = copy.deepcopy(self._data)
49
+ out = fn(data)
50
+ self._data = data
51
+ return out
52
+
53
+
54
+ class FileCheckpointStore:
55
+ """The store the kosa8 CLI, MCP server and desk use (mode 0600, rewritten atomically)."""
56
+
57
+ def __init__(self, path: Optional[str] = None) -> None:
58
+ self.path = path or os.path.join(os.path.expanduser("~"), ".kosa8", "checkpoints.json")
59
+ self._mu = threading.Lock()
60
+
61
+ def load(self) -> StoreData:
62
+ try:
63
+ with open(self.path, "r", encoding="utf-8") as f:
64
+ raw = f.read()
65
+ except FileNotFoundError:
66
+ return {}
67
+ try:
68
+ parsed = json.loads(raw)
69
+ except ValueError:
70
+ return {} # a corrupt store must not make the sandbox unusable (as pkg/checkpoint)
71
+ return parsed if isinstance(parsed, dict) else {}
72
+
73
+ def update(self, fn: Callable[[StoreData], T]) -> T:
74
+ os.makedirs(os.path.dirname(self.path), mode=0o700, exist_ok=True)
75
+ with self._mu:
76
+ fd = os.open(self.path + ".lock", os.O_RDWR | os.O_CREAT, 0o600)
77
+ try:
78
+ try:
79
+ import fcntl
80
+
81
+ fcntl.flock(fd, fcntl.LOCK_EX)
82
+ except ImportError: # Windows: in-process lock only, as pkg/checkpoint lock_other.go
83
+ pass
84
+ data = self.load()
85
+ out = fn(data)
86
+ tmp = self.path + ".tmp"
87
+ with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w", encoding="utf-8") as f:
88
+ json.dump(data, f, indent=2)
89
+ os.replace(tmp, self.path)
90
+ return out
91
+ finally:
92
+ os.close(fd) # closing drops the flock
93
+
94
+
95
+ def _seq_of(cid: str, sandbox: str) -> int:
96
+ pre = sandbox + "-ckpt-"
97
+ if not cid.startswith(pre):
98
+ return 0
99
+ m = re.match(r"^(\d+)", cid[len(pre):])
100
+ return int(m.group(1)) if m else 0
101
+
102
+
103
+ _FRAC = re.compile(r"\.(\d+)")
104
+
105
+
106
+ def _ts(c: Dict[str, Any]) -> float:
107
+ # Go writes RFC 3339 with up to nine fractional digits; Python before 3.11
108
+ # takes exactly six and no "Z", so normalise both before parsing.
109
+ s = (c.get("created") or "").replace("Z", "+00:00")
110
+ s = _FRAC.sub(lambda m: "." + (m.group(1) + "000000")[:6], s, count=1)
111
+ try:
112
+ return datetime.fromisoformat(s).timestamp()
113
+ except ValueError:
114
+ return 0.0
115
+
116
+
117
+ def _sorted(lst: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
118
+ return [c for _, _, c in sorted(((_ts(c), i, c) for i, c in enumerate(lst)), key=lambda x: (x[0], x[1]))]
119
+
120
+
121
+ def _now() -> str:
122
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
123
+
124
+
125
+ class CheckpointBook:
126
+ """The stack logic of pkg/checkpoint, over any store."""
127
+
128
+ def __init__(self, store: Any) -> None:
129
+ self.store = store
130
+
131
+ def next_id(self, sandbox: str) -> Tuple[str, List[str]]:
132
+ """The snapshot id the next checkpoint should use, and ids to evict to stay under the cap."""
133
+ validate_sandbox_name(sandbox)
134
+ lst = self.store.load().get(sandbox, [])
135
+ n = len(lst) + 1
136
+ for c in lst:
137
+ v = _seq_of(c.get("id", ""), sandbox)
138
+ if v >= n:
139
+ n = v + 1
140
+ over = len(lst) + 1 - MAX_CHECKPOINTS_PER_SANDBOX
141
+ evict = [c["id"] for c in lst[:over]] if over > 0 else []
142
+ return f"{sandbox}-ckpt-{n}", evict
143
+
144
+ def record(self, cid: str, sandbox: str, label: str = "", evicted: Optional[List[str]] = None) -> Dict[str, Any]:
145
+ validate_sandbox_name(sandbox)
146
+ rec = {"id": cid, "sandbox": sandbox, "label": label or "", "created": _now()}
147
+ drop = set(evicted or [])
148
+
149
+ def fn(s: StoreData) -> None:
150
+ s[sandbox] = [e for e in s.get(sandbox, []) if e.get("id") not in drop] + [rec]
151
+
152
+ self.store.update(fn)
153
+ return rec
154
+
155
+ def list(self, sandbox: str) -> List[Dict[str, Any]]:
156
+ return _sorted(list(self.store.load().get(sandbox, [])))
157
+
158
+ def latest(self, sandbox: str) -> Dict[str, Any]:
159
+ lst = self.list(sandbox)
160
+ if not lst:
161
+ raise Kosa8CheckpointError(
162
+ f"no checkpoints for {json.dumps(sandbox)} — take one with checkpoint() or `kosa8 checkpoint {sandbox}`"
163
+ )
164
+ return lst[-1]
165
+
166
+ def resolve(self, sandbox: str, ref: str) -> Dict[str, Any]:
167
+ """Find by id or (case-insensitive) label, newest match first."""
168
+ for c in reversed(self.list(sandbox)):
169
+ if c.get("id") == ref or (c.get("label") or "").lower() == ref.lower():
170
+ return c
171
+ raise Kosa8CheckpointError(f"no checkpoint {json.dumps(ref)} for sandbox {json.dumps(sandbox)}")
172
+
173
+ def pop(self, sandbox: str, cid: str) -> List[str]:
174
+ """Keep ``cid`` as the top of the stack; return the ids taken after it."""
175
+
176
+ def fn(s: StoreData) -> List[str]:
177
+ lst = s.get(sandbox, [])
178
+ idx = next((i for i, c in enumerate(lst) if c.get("id") == cid), -1)
179
+ if idx < 0:
180
+ raise Kosa8CheckpointError(f"no checkpoint {json.dumps(cid)} for sandbox {json.dumps(sandbox)}")
181
+ orphaned = [c["id"] for c in lst[idx + 1:]]
182
+ s[sandbox] = lst[: idx + 1]
183
+ return orphaned
184
+
185
+ return self.store.update(fn)
186
+
187
+ def forget(self, sandbox: str) -> List[str]:
188
+ """Drop every checkpoint of a sandbox; return the snapshot ids to delete."""
189
+
190
+ def fn(s: StoreData) -> List[str]:
191
+ ids = [c["id"] for c in s.get(sandbox, [])]
192
+ s.pop(sandbox, None)
193
+ return ids
194
+
195
+ return self.store.update(fn)