klatch 0.1.0.dev0__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.
- klatch-0.1.0.dev0/.gitignore +5 -0
- klatch-0.1.0.dev0/LICENSE +21 -0
- klatch-0.1.0.dev0/PKG-INFO +23 -0
- klatch-0.1.0.dev0/README.md +11 -0
- klatch-0.1.0.dev0/klatch_client.py +220 -0
- klatch-0.1.0.dev0/package/wheel_init.py +7 -0
- klatch-0.1.0.dev0/pyproject.toml +28 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alex Lee
|
|
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.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: klatch
|
|
3
|
+
Version: 0.1.0.dev0
|
|
4
|
+
Summary: A substrate for agent rooms (pre-release; the Python client)
|
|
5
|
+
Project-URL: Homepage, https://github.com/hslee16/klatch
|
|
6
|
+
Project-URL: Source, https://github.com/hslee16/klatch
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# klatch (pre-release)
|
|
14
|
+
|
|
15
|
+
A substrate for agent rooms: claims, asks, offers, status, a board and a durable log.
|
|
16
|
+
|
|
17
|
+
**This is an early pre-release.** It holds only the Python client library (`klatch.client`), which speaks the wire
|
|
18
|
+
protocol (PROTOCOL.md, version 1) to `klatch serve --stdio`. The klatch binary is not in this package yet. It has had
|
|
19
|
+
no outside security review: this is not for sensitive data.
|
|
20
|
+
|
|
21
|
+
Source and documentation: https://github.com/hslee16/klatch
|
|
22
|
+
|
|
23
|
+
Not related to Design-in-Product/klatch.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# klatch (pre-release)
|
|
2
|
+
|
|
3
|
+
A substrate for agent rooms: claims, asks, offers, status, a board and a durable log.
|
|
4
|
+
|
|
5
|
+
**This is an early pre-release.** It holds only the Python client library (`klatch.client`), which speaks the wire
|
|
6
|
+
protocol (PROTOCOL.md, version 1) to `klatch serve --stdio`. The klatch binary is not in this package yet. It has had
|
|
7
|
+
no outside security review: this is not for sensitive data.
|
|
8
|
+
|
|
9
|
+
Source and documentation: https://github.com/hslee16/klatch
|
|
10
|
+
|
|
11
|
+
Not related to Design-in-Product/klatch.
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""A thin klatch client over the wire protocol (PROTOCOL.md, version 1): it speaks newline-delimited JSON to
|
|
2
|
+
`klatch serve --stdio`, standard library only.
|
|
3
|
+
|
|
4
|
+
c = Client("/path/to/klatch", env={"KLATCH_NAME": "alice", ...})
|
|
5
|
+
c.post("lobby", "hello")
|
|
6
|
+
c.subscribe("lobby", from_seq=0); c.collect(until_caught_up=True)
|
|
7
|
+
|
|
8
|
+
Who you are is decided by the transport (the environment of the process), never by a request parameter. A frame this
|
|
9
|
+
version does not know, and a field it does not know, are ignored, as the protocol requires.
|
|
10
|
+
"""
|
|
11
|
+
import json
|
|
12
|
+
import queue
|
|
13
|
+
import subprocess
|
|
14
|
+
import threading
|
|
15
|
+
|
|
16
|
+
PROTOCOL_VERSION = 1
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ProtocolError(Exception):
|
|
20
|
+
"""A frame that is not version 1 of the protocol."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ApiError(Exception):
|
|
24
|
+
"""A failed response. `refusals` are the refusal frames that came with it (a policy refused the call)."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, code, message, refusals=None):
|
|
27
|
+
super().__init__(f"{code}: {message}")
|
|
28
|
+
self.code, self.message, self.refusals = code, message, refusals or []
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def decode_server_frame(line):
|
|
32
|
+
"""One line from the gateway as a dict, or None for a blank line. An unknown type or field is not an error; a
|
|
33
|
+
line that is not a JSON object with `"v":1` and a `type` is."""
|
|
34
|
+
if not line.strip():
|
|
35
|
+
return None
|
|
36
|
+
try:
|
|
37
|
+
frame = json.loads(line)
|
|
38
|
+
except ValueError as e:
|
|
39
|
+
raise ProtocolError(f"not JSON: {e}") from None
|
|
40
|
+
if not isinstance(frame, dict):
|
|
41
|
+
raise ProtocolError("a frame is a JSON object")
|
|
42
|
+
v = frame.get("v")
|
|
43
|
+
if isinstance(v, bool) or not isinstance(v, int) or v != PROTOCOL_VERSION:
|
|
44
|
+
raise ProtocolError(f"protocol version {v!r} is not supported; this client speaks {PROTOCOL_VERSION}")
|
|
45
|
+
if not isinstance(frame.get("type"), str):
|
|
46
|
+
raise ProtocolError("a frame has a type")
|
|
47
|
+
return frame
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def encode_line(frame):
|
|
51
|
+
return json.dumps({"v": PROTOCOL_VERSION, **frame}, separators=(",", ":")) + "\n"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Client:
|
|
55
|
+
"""One session with the gateway. Not thread safe: use one client per thread."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, binary, env=None, args=("serve", "--stdio")):
|
|
58
|
+
self._proc = subprocess.Popen(
|
|
59
|
+
[binary, *args],
|
|
60
|
+
env=env,
|
|
61
|
+
stdin=subprocess.PIPE,
|
|
62
|
+
stdout=subprocess.PIPE,
|
|
63
|
+
stderr=subprocess.DEVNULL,
|
|
64
|
+
text=True,
|
|
65
|
+
bufsize=1,
|
|
66
|
+
)
|
|
67
|
+
self._frames = queue.Queue()
|
|
68
|
+
self._next_id = 0
|
|
69
|
+
self.refusals = []
|
|
70
|
+
self._pending_messages = []
|
|
71
|
+
self._caught_up = {}
|
|
72
|
+
threading.Thread(target=self._pump, daemon=True).start()
|
|
73
|
+
hello = self._frame(timeout=10)
|
|
74
|
+
if hello is None or hello.get("type") != "hello":
|
|
75
|
+
raise ProtocolError("the first frame is hello")
|
|
76
|
+
self.member = hello["member"]
|
|
77
|
+
self.attribution = hello["attribution"]
|
|
78
|
+
self.clearance = hello["clearance"]
|
|
79
|
+
|
|
80
|
+
# ---- reading ----
|
|
81
|
+
|
|
82
|
+
def _pump(self):
|
|
83
|
+
for line in self._proc.stdout:
|
|
84
|
+
try:
|
|
85
|
+
frame = decode_server_frame(line)
|
|
86
|
+
except ProtocolError as e:
|
|
87
|
+
frame = {"type": "_error", "error": str(e)}
|
|
88
|
+
if frame is not None:
|
|
89
|
+
self._frames.put(frame)
|
|
90
|
+
self._frames.put(None)
|
|
91
|
+
|
|
92
|
+
def _frame(self, timeout):
|
|
93
|
+
try:
|
|
94
|
+
return self._frames.get(timeout=timeout)
|
|
95
|
+
except queue.Empty:
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
def _note(self, frame):
|
|
99
|
+
"""Keep what a response is not: messages, caught-up marks, refusals. Heartbeats and unknown types go."""
|
|
100
|
+
kind = frame.get("type")
|
|
101
|
+
if kind == "message":
|
|
102
|
+
self._pending_messages.append(frame)
|
|
103
|
+
elif kind == "caught_up":
|
|
104
|
+
self._caught_up[frame["room"]] = frame
|
|
105
|
+
elif kind == "refusal":
|
|
106
|
+
self.refusals.append(frame)
|
|
107
|
+
|
|
108
|
+
# ---- requests ----
|
|
109
|
+
|
|
110
|
+
def request(self, method, **params):
|
|
111
|
+
"""Send a request and return its result, or raise ApiError. Frames that arrive meanwhile are kept."""
|
|
112
|
+
self._next_id += 1
|
|
113
|
+
rid = f"c{self._next_id}"
|
|
114
|
+
self.refusals = []
|
|
115
|
+
self._send({"type": "request", "id": rid, "method": method, "params": params})
|
|
116
|
+
while True:
|
|
117
|
+
frame = self._frame(timeout=30)
|
|
118
|
+
if frame is None:
|
|
119
|
+
raise ProtocolError("the gateway closed the session or did not answer")
|
|
120
|
+
if frame.get("type") == "response" and frame.get("id") == rid:
|
|
121
|
+
if frame.get("ok"):
|
|
122
|
+
return frame.get("result") or {}
|
|
123
|
+
err = frame.get("error") or {}
|
|
124
|
+
raise ApiError(err.get("code", "backend"), err.get("message", ""), list(self.refusals))
|
|
125
|
+
self._note(frame)
|
|
126
|
+
|
|
127
|
+
def _send(self, frame):
|
|
128
|
+
self._proc.stdin.write(encode_line(frame))
|
|
129
|
+
self._proc.stdin.flush()
|
|
130
|
+
|
|
131
|
+
def post(self, room, body, label=None, kind=None, payload=None):
|
|
132
|
+
params = {"room": room, "body": body}
|
|
133
|
+
for k, v in (("label", label), ("kind", kind), ("payload", payload)):
|
|
134
|
+
if v is not None:
|
|
135
|
+
params[k] = v
|
|
136
|
+
return self.request("post", **params)
|
|
137
|
+
|
|
138
|
+
def read(self, room, peek=False):
|
|
139
|
+
return self.request("read", room=room, peek=peek)["messages"]
|
|
140
|
+
|
|
141
|
+
def claim(self, room, path, ttl=None, reason=None, shared=None):
|
|
142
|
+
params = {"room": room, "path": path}
|
|
143
|
+
for k, v in (("ttl", ttl), ("reason", reason), ("shared", shared)):
|
|
144
|
+
if v is not None:
|
|
145
|
+
params[k] = v
|
|
146
|
+
self.request("claim", **params)
|
|
147
|
+
|
|
148
|
+
def release(self, room, path, note=None):
|
|
149
|
+
params = {"room": room, "path": path}
|
|
150
|
+
if note is not None:
|
|
151
|
+
params["note"] = note
|
|
152
|
+
self.request("release", **params)
|
|
153
|
+
|
|
154
|
+
def claims(self, room):
|
|
155
|
+
return self.request("claims", room=room)["claims"]
|
|
156
|
+
|
|
157
|
+
def who(self, room):
|
|
158
|
+
return self.request("who", room=room)["members"]
|
|
159
|
+
|
|
160
|
+
def set_status(self, room, status):
|
|
161
|
+
self.request("status", room=room, status=status)
|
|
162
|
+
|
|
163
|
+
def subscribe(self, room, from_seq=0):
|
|
164
|
+
"""Start (or resume) a stream; returns the room's head. Messages arrive through `collect` and `next_message`."""
|
|
165
|
+
self._caught_up.pop(room, None)
|
|
166
|
+
return self.request("subscribe", room=room, from_seq=from_seq)["head"]
|
|
167
|
+
|
|
168
|
+
def unsubscribe(self, room):
|
|
169
|
+
self.request("unsubscribe", room=room)
|
|
170
|
+
|
|
171
|
+
def ack(self, room, seq):
|
|
172
|
+
self._send({"type": "ack", "room": room, "seq": seq})
|
|
173
|
+
|
|
174
|
+
# ---- the stream ----
|
|
175
|
+
|
|
176
|
+
def collect(self, until_caught_up=False, timeout=10):
|
|
177
|
+
"""Messages received so far; with `until_caught_up`, wait for the replay to finish first."""
|
|
178
|
+
import time
|
|
179
|
+
|
|
180
|
+
end = time.monotonic() + timeout
|
|
181
|
+
while until_caught_up and not self._caught_up and time.monotonic() < end:
|
|
182
|
+
frame = self._frame(timeout=max(0.0, end - time.monotonic()))
|
|
183
|
+
if frame is None:
|
|
184
|
+
break
|
|
185
|
+
self._note(frame)
|
|
186
|
+
messages, self._pending_messages = self._pending_messages, []
|
|
187
|
+
caught_up = next(iter(self._caught_up.values()), None)
|
|
188
|
+
return {"messages": messages, "caught_up": caught_up}
|
|
189
|
+
|
|
190
|
+
def next_message(self, timeout=10):
|
|
191
|
+
"""The next message of a subscription, waiting for it; None on timeout."""
|
|
192
|
+
import time
|
|
193
|
+
|
|
194
|
+
end = time.monotonic() + timeout
|
|
195
|
+
while True:
|
|
196
|
+
if self._pending_messages:
|
|
197
|
+
return self._pending_messages.pop(0)
|
|
198
|
+
frame = self._frame(timeout=max(0.0, end - time.monotonic()))
|
|
199
|
+
if frame is None:
|
|
200
|
+
return None
|
|
201
|
+
self._note(frame)
|
|
202
|
+
|
|
203
|
+
def close(self):
|
|
204
|
+
"""End the session: close the input, which ends the gateway's side. Returns its exit code."""
|
|
205
|
+
if self._proc.poll() is None:
|
|
206
|
+
try:
|
|
207
|
+
self._proc.stdin.close()
|
|
208
|
+
except OSError:
|
|
209
|
+
pass
|
|
210
|
+
try:
|
|
211
|
+
self._proc.wait(timeout=10)
|
|
212
|
+
except subprocess.TimeoutExpired:
|
|
213
|
+
self._proc.kill()
|
|
214
|
+
self._proc.wait()
|
|
215
|
+
for stream in (self._proc.stdin, self._proc.stdout):
|
|
216
|
+
try:
|
|
217
|
+
stream.close()
|
|
218
|
+
except OSError:
|
|
219
|
+
pass
|
|
220
|
+
return self._proc.returncode
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""klatch: a substrate for agent rooms. This package is a pre-release; see the repository.
|
|
2
|
+
|
|
3
|
+
The wheel installs this file (package/wheel_init.py) as `klatch/__init__.py` and `klatch_client.py` as `klatch/client.py`.
|
|
4
|
+
"""
|
|
5
|
+
from .client import ApiError, Client, PROTOCOL_VERSION, ProtocolError # noqa: F401
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0.dev0"
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "klatch"
|
|
7
|
+
version = "0.1.0.dev0"
|
|
8
|
+
description = "A substrate for agent rooms (pre-release; the Python client)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
classifiers = ["Development Status :: 2 - Pre-Alpha"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://github.com/hslee16/klatch"
|
|
17
|
+
Source = "https://github.com/hslee16/klatch"
|
|
18
|
+
|
|
19
|
+
# klatch_client.py stays the one source of the client; the wheel carries it as klatch/client.py.
|
|
20
|
+
[tool.hatch.build.targets.wheel]
|
|
21
|
+
bypass-selection = true
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
24
|
+
"package/wheel_init.py" = "klatch/__init__.py"
|
|
25
|
+
"klatch_client.py" = "klatch/client.py"
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.sdist]
|
|
28
|
+
include = ["package/wheel_init.py", "klatch_client.py", "README.md", "LICENSE", "pyproject.toml"]
|