deft-subspace-kernel 0.1.0a1__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.
- deft_subspace/kernel/__init__.py +93 -0
- deft_subspace/kernel/abort.py +173 -0
- deft_subspace/kernel/channel.py +244 -0
- deft_subspace/kernel/clock.py +39 -0
- deft_subspace/kernel/errors.py +114 -0
- deft_subspace/kernel/framing.py +171 -0
- deft_subspace/kernel/process.py +614 -0
- deft_subspace/kernel/py.typed +0 -0
- deft_subspace/kernel/rpc.py +815 -0
- deft_subspace/kernel/testing.py +97 -0
- deft_subspace/kernel/trace.py +143 -0
- deft_subspace_kernel-0.1.0a1.dist-info/METADATA +41 -0
- deft_subspace_kernel-0.1.0a1.dist-info/RECORD +15 -0
- deft_subspace_kernel-0.1.0a1.dist-info/WHEEL +4 -0
- deft_subspace_kernel-0.1.0a1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Test helpers: a clock you move by hand, and faults you can put on a byte
|
|
2
|
+
stream (tiny chunks, merged chunks) to prove framing does not care how bytes arrive."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
from collections.abc import Callable, Iterable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ManualClock:
|
|
12
|
+
def __init__(self, start: float = 0) -> None:
|
|
13
|
+
self._now = start
|
|
14
|
+
self._next = 1
|
|
15
|
+
self._timers: dict[int, tuple[float, Callable[[], None]]] = {}
|
|
16
|
+
|
|
17
|
+
def now(self) -> float:
|
|
18
|
+
return self._now
|
|
19
|
+
|
|
20
|
+
def set_timeout(self, callback: Callable[[], None], ms: float) -> int:
|
|
21
|
+
handle = self._next
|
|
22
|
+
self._next += 1
|
|
23
|
+
self._timers[handle] = (self._now + max(0, ms), callback)
|
|
24
|
+
return handle
|
|
25
|
+
|
|
26
|
+
def clear_timeout(self, handle: Any) -> None:
|
|
27
|
+
self._timers.pop(handle, None)
|
|
28
|
+
|
|
29
|
+
def advance(self, ms: float) -> None:
|
|
30
|
+
"""Move time forward, running every timer that comes due, in order."""
|
|
31
|
+
target = self._now + ms
|
|
32
|
+
while True:
|
|
33
|
+
due = [(at, handle) for handle, (at, _cb) in self._timers.items() if at <= target]
|
|
34
|
+
if not due:
|
|
35
|
+
break
|
|
36
|
+
at, handle = min(due)
|
|
37
|
+
_at, callback = self._timers.pop(handle)
|
|
38
|
+
self._now = at
|
|
39
|
+
callback()
|
|
40
|
+
self._now = target
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def pending_timers(self) -> int:
|
|
44
|
+
return len(self._timers)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def manual_clock(start: float = 0) -> ManualClock:
|
|
48
|
+
return ManualClock(start)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Rechunk:
|
|
52
|
+
"""Re-chunk bytes into pieces of `size` bytes (1 = byte by byte)."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, size: int) -> None:
|
|
55
|
+
self._size = size
|
|
56
|
+
|
|
57
|
+
def feed(self, chunk: bytes) -> Iterable[bytes]:
|
|
58
|
+
return [chunk[i : i + self._size] for i in range(0, len(chunk), self._size)]
|
|
59
|
+
|
|
60
|
+
def flush(self) -> Iterable[bytes]:
|
|
61
|
+
return ()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Merge:
|
|
65
|
+
"""Hold bytes and release them merged, every `count` chunks (and at the end)."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, count: int) -> None:
|
|
68
|
+
self._count = count
|
|
69
|
+
self._held: list[bytes] = []
|
|
70
|
+
|
|
71
|
+
def feed(self, chunk: bytes) -> Iterable[bytes]:
|
|
72
|
+
self._held.append(chunk)
|
|
73
|
+
return self._release() if len(self._held) >= self._count else ()
|
|
74
|
+
|
|
75
|
+
def flush(self) -> Iterable[bytes]:
|
|
76
|
+
return self._release()
|
|
77
|
+
|
|
78
|
+
def _release(self) -> list[bytes]:
|
|
79
|
+
if not self._held:
|
|
80
|
+
return []
|
|
81
|
+
out = b"".join(self._held)
|
|
82
|
+
self._held = []
|
|
83
|
+
return [out]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def rechunk(size: int) -> Rechunk:
|
|
87
|
+
return Rechunk(size)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def merge(count: int) -> Merge:
|
|
91
|
+
return Merge(count)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def tick(times: int = 10) -> None:
|
|
95
|
+
"""Let pending tasks run (a few loop iterations)."""
|
|
96
|
+
for _ in range(times):
|
|
97
|
+
await asyncio.sleep(0)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Traces: every JSON-RPC message on a connection, with time and direction, as JSON Lines.
|
|
2
|
+
|
|
3
|
+
One format for recording, replay, and the trace viewer, the same as the
|
|
4
|
+
TypeScript packages write.
|
|
5
|
+
|
|
6
|
+
records = []
|
|
7
|
+
peer = RpcPeer(channel, tap=trace_tap(records.append, peer="client"))
|
|
8
|
+
...
|
|
9
|
+
Path("session.trace.jsonl").write_text(format_trace(records))
|
|
10
|
+
|
|
11
|
+
Line 1 is a header. Then one record per message (and optional notes).
|
|
12
|
+
`t` is milliseconds since the header's `started`.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import copy
|
|
18
|
+
import json
|
|
19
|
+
from collections.abc import Callable, Sequence
|
|
20
|
+
from datetime import datetime, timezone
|
|
21
|
+
from typing import Any, Literal
|
|
22
|
+
|
|
23
|
+
from .clock import Clock, system_clock
|
|
24
|
+
|
|
25
|
+
TRACE_VERSION = 1
|
|
26
|
+
|
|
27
|
+
TraceRecord = dict[str, Any]
|
|
28
|
+
"""`{"v": 1, "kind": "header" | "message" | "note", ...}`; see the module docstring."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
_NO_DATA: Any = object()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _iso(ms: float) -> str:
|
|
35
|
+
stamp = datetime.fromtimestamp(ms / 1000, tz=timezone.utc)
|
|
36
|
+
return stamp.strftime("%Y-%m-%dT%H:%M:%S.") + f"{stamp.microsecond // 1000:03d}Z"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
#: Past this depth the direct copy gives up (cycles end here, and the stack stays small).
|
|
40
|
+
_MAX_DEPTH = 256
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _TooDeep(Exception):
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _copy_message(value: Any) -> Any:
|
|
48
|
+
"""A copy of a message, so later mutation does not change the record. Dicts and lists
|
|
49
|
+
(all JSON has) are copied directly, many times faster than `copy.deepcopy`; anything
|
|
50
|
+
else goes to `copy.deepcopy`. A message nested deeper than any real one (a cycle, say)
|
|
51
|
+
is given to `copy.deepcopy` whole, which keeps cycles; one that cannot be copied at all
|
|
52
|
+
is recorded as it is. Never raises."""
|
|
53
|
+
try:
|
|
54
|
+
return _copy_json(value, 0)
|
|
55
|
+
except Exception:
|
|
56
|
+
try:
|
|
57
|
+
return copy.deepcopy(value)
|
|
58
|
+
except Exception:
|
|
59
|
+
return value
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _copy_json(value: Any, depth: int) -> Any:
|
|
63
|
+
kind = type(value)
|
|
64
|
+
if kind is str or kind is int or kind is float or kind is bool or value is None:
|
|
65
|
+
return value
|
|
66
|
+
if depth > _MAX_DEPTH:
|
|
67
|
+
raise _TooDeep
|
|
68
|
+
if kind is dict:
|
|
69
|
+
return {k: _copy_json(v, depth + 1) for k, v in value.items()}
|
|
70
|
+
if kind is list:
|
|
71
|
+
return [_copy_json(v, depth + 1) for v in value]
|
|
72
|
+
return copy.deepcopy(value)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class TraceTap:
|
|
76
|
+
"""A peer `tap` that records a trace. The header is written at once."""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
write: Callable[[TraceRecord], None],
|
|
81
|
+
*,
|
|
82
|
+
peer: str,
|
|
83
|
+
label: str | None = None,
|
|
84
|
+
meta: dict[str, Any] | None = None,
|
|
85
|
+
clock: Clock | None = None,
|
|
86
|
+
redact: Callable[[Any, Literal["in", "out"]], Any] | None = None,
|
|
87
|
+
) -> None:
|
|
88
|
+
"""`redact` may change a message or drop it (return None) before it is recorded, e.g. to remove secrets."""
|
|
89
|
+
self._write = write
|
|
90
|
+
self._clock = clock or system_clock
|
|
91
|
+
self._redact = redact
|
|
92
|
+
self._start = self._clock.now()
|
|
93
|
+
header: TraceRecord = {"v": TRACE_VERSION, "kind": "header", "started": _iso(self._start), "peer": peer}
|
|
94
|
+
if label:
|
|
95
|
+
header["label"] = label
|
|
96
|
+
if meta:
|
|
97
|
+
header["meta"] = meta
|
|
98
|
+
write(header)
|
|
99
|
+
|
|
100
|
+
def __call__(self, direction: Literal["in", "out"], message: Any) -> None:
|
|
101
|
+
msg = self._redact(message, direction) if self._redact else message
|
|
102
|
+
if msg is None:
|
|
103
|
+
return
|
|
104
|
+
# Copy, so later mutation of the message does not change the record.
|
|
105
|
+
self._write({"v": TRACE_VERSION, "kind": "message", "t": self._elapsed(), "dir": direction, "msg": _copy_message(msg)})
|
|
106
|
+
|
|
107
|
+
def note(self, text: str, data: Any = _NO_DATA) -> None:
|
|
108
|
+
"""Add a note at the current time. `data=None` is recorded as null; leave it out for no data."""
|
|
109
|
+
record: TraceRecord = {"v": TRACE_VERSION, "kind": "note", "t": self._elapsed(), "text": text}
|
|
110
|
+
if data is not _NO_DATA:
|
|
111
|
+
record["data"] = data
|
|
112
|
+
self._write(record)
|
|
113
|
+
|
|
114
|
+
def _elapsed(self) -> float:
|
|
115
|
+
elapsed = self._clock.now() - self._start
|
|
116
|
+
return int(elapsed) if float(elapsed).is_integer() else elapsed
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def trace_tap(write: Callable[[TraceRecord], None], **options: Any) -> TraceTap:
|
|
120
|
+
return TraceTap(write, **options)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def format_trace(records: Sequence[TraceRecord]) -> str:
|
|
124
|
+
"""Records as JSON Lines."""
|
|
125
|
+
return "".join(json.dumps(r, ensure_ascii=False, separators=(",", ":")) + "\n" for r in records)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def parse_trace(text: str) -> list[TraceRecord]:
|
|
129
|
+
"""Parse JSON Lines. Raises ValueError on a malformed line, naming it; skips blank lines."""
|
|
130
|
+
records: list[TraceRecord] = []
|
|
131
|
+
for index, line in enumerate(text.split("\n")):
|
|
132
|
+
if not line.strip():
|
|
133
|
+
continue
|
|
134
|
+
try:
|
|
135
|
+
record = json.loads(line)
|
|
136
|
+
except ValueError as error:
|
|
137
|
+
raise ValueError(f"Trace line {index + 1} is not JSON") from error
|
|
138
|
+
if not isinstance(record, dict) or record.get("v") != TRACE_VERSION or record.get("kind") not in ("header", "message", "note"):
|
|
139
|
+
raise ValueError(f"Trace line {index + 1} is not a version {TRACE_VERSION} trace record")
|
|
140
|
+
records.append(record)
|
|
141
|
+
if not records or records[0].get("kind") != "header":
|
|
142
|
+
raise ValueError("A trace starts with a header record")
|
|
143
|
+
return records
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: deft-subspace-kernel
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Protocol-neutral kernel: channels, NDJSON framing, a JSON-RPC peer with one owner for every request's lifecycle, and supervised agent processes. No dependencies.
|
|
5
|
+
Project-URL: Homepage, https://github.com/deftai/subspace/tree/main/python
|
|
6
|
+
Project-URL: Source, https://github.com/deftai/subspace
|
|
7
|
+
Project-URL: Issues, https://github.com/deftai/subspace/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/deftai/subspace/blob/main/python/CHANGELOG.md
|
|
9
|
+
Author: Deft
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: acp,agent-client-protocol,asyncio,json-rpc,ndjson
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# deft-subspace-kernel
|
|
27
|
+
|
|
28
|
+
The protocol-neutral kernel of [Deft Subspace for Python](https://github.com/deftai/subspace/tree/main/python): channels, NDJSON framing, a JSON-RPC 2.0 peer (timeouts, cancellation, middleware, one owner for every request), abort signals, traces, and supervised child processes. Plain asyncio, Python 3.11 or later, no dependencies.
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from deft_subspace.kernel import RpcPeer, channel_pair
|
|
32
|
+
|
|
33
|
+
a, b = channel_pair()
|
|
34
|
+
server = RpcPeer(b).on_request("echo", lambda params, _ctx: params).start()
|
|
35
|
+
client = RpcPeer(a).start()
|
|
36
|
+
assert await client.request("echo", {"hi": 1}) == {"hi": 1}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Most programs want [`deft-subspace-acp`](https://pypi.org/project/deft-subspace-acp/), which builds the Agent Client Protocol on this.
|
|
40
|
+
|
|
41
|
+
MIT licensed.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
deft_subspace/kernel/__init__.py,sha256=OWC4Efho3SJxLV6lb4H001K-o_L-x6VbtOtucCBa2Eo,2133
|
|
2
|
+
deft_subspace/kernel/abort.py,sha256=KI8f7umZeY1WxY7bB5IPCx2TLhI_Xl11NiG1Z-l-A5g,5641
|
|
3
|
+
deft_subspace/kernel/channel.py,sha256=SyluAcJk0DpylZHkPNWtFWwj80BEvmy0StrKMunk41w,7610
|
|
4
|
+
deft_subspace/kernel/clock.py,sha256=RyO_GQhqPTE_hL5oHDpoP2kNtIt9XvquLAmMczdmFos,1057
|
|
5
|
+
deft_subspace/kernel/errors.py,sha256=6p0bpHGm721x6LPCGySAzXCeNtkw6wnEXcx8XOnQDYM,3944
|
|
6
|
+
deft_subspace/kernel/framing.py,sha256=VO9bnrKOmJJoeRirxaDv2v0wG0yKeTc7Lra67bKVD-c,6146
|
|
7
|
+
deft_subspace/kernel/process.py,sha256=a97WGSJkPdm0yDj8gKuU98ujEZleY1MCII78sAq1Rdo,24734
|
|
8
|
+
deft_subspace/kernel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
deft_subspace/kernel/rpc.py,sha256=RdxDoqKDp7fKAABobSRfKvtopJ90wygDMQbUwsZxUmY,34940
|
|
10
|
+
deft_subspace/kernel/testing.py,sha256=P1JPBiDLlMCS7YH1Hssg2ft3Ah3IGy0S1HqShGN5kFw,2731
|
|
11
|
+
deft_subspace/kernel/trace.py,sha256=6FbPfiPpY0NVXPlPWpxAd3UFisRU0nlNG8e_I0-nVUw,5243
|
|
12
|
+
deft_subspace_kernel-0.1.0a1.dist-info/METADATA,sha256=7xb9YwkMQMGkMdYBjEUmUYQTe9HDpVUqU-W4AtwMZ9w,1918
|
|
13
|
+
deft_subspace_kernel-0.1.0a1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
deft_subspace_kernel-0.1.0a1.dist-info/licenses/LICENSE,sha256=vKS3QRL1vc6MvWI3BRsUYGxchuYOW6LRFSVtnSAnkQ4,1061
|
|
15
|
+
deft_subspace_kernel-0.1.0a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Deft
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|