reef-client 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.
- reef_client/__init__.py +23 -0
- reef_client/client.py +309 -0
- reef_client/serve.py +472 -0
- reef_client/skill.py +43 -0
- reef_client/sse.py +182 -0
- reef_client-0.1.0.dist-info/METADATA +63 -0
- reef_client-0.1.0.dist-info/RECORD +10 -0
- reef_client-0.1.0.dist-info/WHEEL +5 -0
- reef_client-0.1.0.dist-info/licenses/LICENSE +201 -0
- reef_client-0.1.0.dist-info/top_level.txt +1 -0
reef_client/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Stdlib-only SDK for harnesses talking to a Reef service.
|
|
2
|
+
|
|
3
|
+
Components: ``client`` (the ask/observe/report loop), ``skill`` (fetch and
|
|
4
|
+
sync the served skill file), ``sse`` (stream synthesis/accumulation), and
|
|
5
|
+
``serve`` (a local sidecar agents treat as their model endpoint).
|
|
6
|
+
Everything is standard library only, so external harnesses can copy or
|
|
7
|
+
import the package with no dependency on the ``reef`` package.
|
|
8
|
+
|
|
9
|
+
The client and skill helpers are re-exported here; import the ``sse`` and
|
|
10
|
+
``serve`` submodules directly (``from reef_client.serve import ServeConfig``)
|
|
11
|
+
so ``python -m reef_client.serve`` stays the single import of that module.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from reef_client.client import ReefClient, ReefClientError
|
|
15
|
+
from reef_client.skill import SkillNotServedError, fetch_skill, sync_skill
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"ReefClient",
|
|
19
|
+
"ReefClientError",
|
|
20
|
+
"SkillNotServedError",
|
|
21
|
+
"fetch_skill",
|
|
22
|
+
"sync_skill",
|
|
23
|
+
]
|
reef_client/client.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Stdlib-only client that external harnesses can copy or import."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from pathlib import Path, PurePosixPath
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
#: Where ``harness_pull`` records the pulled version inside the destination.
|
|
14
|
+
#: Client-side bookkeeping only: the sidecar is written beside the pulled
|
|
15
|
+
#: tree, never served, and not part of the byte-identity claim on the tree.
|
|
16
|
+
HARNESS_VERSION_SIDECAR = ".reef-harness-version"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ReefClientError(RuntimeError):
|
|
20
|
+
"""The service answered >= 400. ``content_type`` is the bare mime type
|
|
21
|
+
(parameters like charset stripped), mirroring aiohttp's ``.content_type``."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, status: int, body: str, content_type: str | None = None) -> None:
|
|
24
|
+
super().__init__(f"Reef service returned {status}: {body[:400]}")
|
|
25
|
+
self.status = status
|
|
26
|
+
self.body = body
|
|
27
|
+
self.content_type = content_type.split(";")[0].strip() if content_type else None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ReefClient:
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
service_url: str,
|
|
34
|
+
*,
|
|
35
|
+
token: str | None = None,
|
|
36
|
+
timeout_s: float = 30.0,
|
|
37
|
+
) -> None:
|
|
38
|
+
self.service_url = service_url.rstrip("/")
|
|
39
|
+
self.token = token
|
|
40
|
+
self.timeout_s = timeout_s
|
|
41
|
+
|
|
42
|
+
def inference(
|
|
43
|
+
self,
|
|
44
|
+
scenario: str,
|
|
45
|
+
path: str,
|
|
46
|
+
payload: Mapping[str, Any],
|
|
47
|
+
*,
|
|
48
|
+
recipe: str | None = None,
|
|
49
|
+
artifact_version: str | None = None,
|
|
50
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
51
|
+
) -> dict[str, Any]:
|
|
52
|
+
return self._post(
|
|
53
|
+
path,
|
|
54
|
+
scenario,
|
|
55
|
+
payload,
|
|
56
|
+
recipe=recipe,
|
|
57
|
+
artifact_version=artifact_version,
|
|
58
|
+
extra_headers=extra_headers,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
def inference_with_record(
|
|
62
|
+
self,
|
|
63
|
+
scenario: str,
|
|
64
|
+
path: str,
|
|
65
|
+
payload: Mapping[str, Any],
|
|
66
|
+
*,
|
|
67
|
+
recipe: str | None = None,
|
|
68
|
+
artifact_version: str | None = None,
|
|
69
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
70
|
+
) -> tuple[dict[str, Any], str]:
|
|
71
|
+
body, headers = self.post(
|
|
72
|
+
path,
|
|
73
|
+
scenario,
|
|
74
|
+
payload,
|
|
75
|
+
recipe=recipe,
|
|
76
|
+
artifact_version=artifact_version,
|
|
77
|
+
extra_headers=extra_headers,
|
|
78
|
+
)
|
|
79
|
+
agent_data_id = headers.get("x-reef-agent-data-id")
|
|
80
|
+
if not agent_data_id:
|
|
81
|
+
raise ReefClientError(502, "inference response is missing x-reef-agent-data-id")
|
|
82
|
+
return body, agent_data_id
|
|
83
|
+
|
|
84
|
+
def report(
|
|
85
|
+
self,
|
|
86
|
+
scenario: str,
|
|
87
|
+
payload: Mapping[str, Any] | Any,
|
|
88
|
+
*,
|
|
89
|
+
references: Sequence[str] | None = None,
|
|
90
|
+
recipe: str | None = None,
|
|
91
|
+
artifact_version: str | None = None,
|
|
92
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
93
|
+
) -> dict[str, Any]:
|
|
94
|
+
"""POST a report: a plain wire dict, or a typed signal instance.
|
|
95
|
+
|
|
96
|
+
Any object with a ``to_report(references=...)`` method (a recipe's
|
|
97
|
+
declared ``reef.schemas.ReportSchema`` dataclass) is serialized through it,
|
|
98
|
+
so the report body is built — and validated — by the contract's own
|
|
99
|
+
code before the request leaves the process. ``references`` are the
|
|
100
|
+
inference ``x-reef-agent-data-id`` receipts this report grades; with
|
|
101
|
+
a plain dict they merge into the payload (the dict's own
|
|
102
|
+
``references`` key wins).
|
|
103
|
+
"""
|
|
104
|
+
to_report = getattr(payload, "to_report", None)
|
|
105
|
+
if callable(to_report):
|
|
106
|
+
payload = to_report(references=tuple(references or ()))
|
|
107
|
+
elif references is not None:
|
|
108
|
+
payload = {"references": list(references), **payload}
|
|
109
|
+
return self._post(
|
|
110
|
+
"/reef/report",
|
|
111
|
+
scenario,
|
|
112
|
+
payload,
|
|
113
|
+
recipe=recipe,
|
|
114
|
+
artifact_version=artifact_version,
|
|
115
|
+
extra_headers=extra_headers,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def post(
|
|
119
|
+
self,
|
|
120
|
+
path: str,
|
|
121
|
+
scenario: str,
|
|
122
|
+
payload: Mapping[str, Any],
|
|
123
|
+
*,
|
|
124
|
+
recipe: str | None = None,
|
|
125
|
+
artifact_version: str | None = None,
|
|
126
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
127
|
+
) -> tuple[dict[str, Any], Mapping[str, str]]:
|
|
128
|
+
"""POST an arbitrary protocol path; return (parsed body, response headers).
|
|
129
|
+
|
|
130
|
+
This is the low-level entry point behind ``inference``/``report``,
|
|
131
|
+
exposed for callers that need the response headers (e.g. a
|
|
132
|
+
forwarding proxy capturing the ``x-reef-agent-data-id`` receipt, where
|
|
133
|
+
a missing receipt is tolerated rather than an error) or that mirror
|
|
134
|
+
upstream behavior. Response header names are lowercased.
|
|
135
|
+
"""
|
|
136
|
+
return self._post_with_headers(
|
|
137
|
+
path,
|
|
138
|
+
scenario,
|
|
139
|
+
payload,
|
|
140
|
+
recipe=recipe,
|
|
141
|
+
artifact_version=artifact_version,
|
|
142
|
+
extra_headers=extra_headers,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def get(
|
|
146
|
+
self,
|
|
147
|
+
path: str,
|
|
148
|
+
*,
|
|
149
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
150
|
+
) -> dict[str, Any]:
|
|
151
|
+
"""GET an arbitrary protocol path and return the parsed JSON body.
|
|
152
|
+
|
|
153
|
+
Read-side counterpart of ``post`` (e.g.
|
|
154
|
+
``/reef/scenarios/{scenario}/versions``). On HTTP errors the raised
|
|
155
|
+
``ReefClientError`` carries ``.status``, so callers can distinguish a
|
|
156
|
+
not-yet-created scenario (404) from a failed probe.
|
|
157
|
+
"""
|
|
158
|
+
headers: dict[str, str] = {}
|
|
159
|
+
if self.token:
|
|
160
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
161
|
+
covered = {name.lower() for name in headers}
|
|
162
|
+
headers.update({name: value for name, value in (extra_headers or {}).items() if name.lower() not in covered})
|
|
163
|
+
request = urllib.request.Request(f"{self.service_url}{path}", headers=headers, method="GET")
|
|
164
|
+
try:
|
|
165
|
+
with urllib.request.urlopen(request, timeout=self.timeout_s) as response:
|
|
166
|
+
body = response.read().decode()
|
|
167
|
+
except urllib.error.HTTPError as exc:
|
|
168
|
+
body = exc.read().decode(errors="replace")
|
|
169
|
+
raise ReefClientError(exc.code, body, exc.headers.get("Content-Type")) from exc
|
|
170
|
+
return json.loads(body) if body else {}
|
|
171
|
+
|
|
172
|
+
def harness_versions(
|
|
173
|
+
self,
|
|
174
|
+
scenario: str,
|
|
175
|
+
*,
|
|
176
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
177
|
+
) -> list[dict[str, Any]]:
|
|
178
|
+
"""List the scenario's harness versions with their gate metrics, newest last.
|
|
179
|
+
|
|
180
|
+
Reads ``GET /reef/harness/versions``: one row per committed version,
|
|
181
|
+
training rows carrying the metrics of the step that published them.
|
|
182
|
+
Any listed version can be pulled with ``harness_pull(version=...)``.
|
|
183
|
+
"""
|
|
184
|
+
headers = {"x-reef-scenario": scenario}
|
|
185
|
+
covered = {name.lower() for name in headers}
|
|
186
|
+
headers.update({name: value for name, value in (extra_headers or {}).items() if name.lower() not in covered})
|
|
187
|
+
body = self.get("/reef/harness/versions", extra_headers=headers)
|
|
188
|
+
versions = body.get("versions", [])
|
|
189
|
+
if not isinstance(versions, list):
|
|
190
|
+
raise ReefClientError(502, "harness versions response carries no versions list")
|
|
191
|
+
return versions
|
|
192
|
+
|
|
193
|
+
def harness_pull(
|
|
194
|
+
self,
|
|
195
|
+
scenario: str,
|
|
196
|
+
destination: str | Path,
|
|
197
|
+
*,
|
|
198
|
+
version: str | None = None,
|
|
199
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
200
|
+
) -> str:
|
|
201
|
+
"""Pull a served harness tree into ``destination`` and return its version.
|
|
202
|
+
|
|
203
|
+
Reads the manifest (``GET /reef/harness``, version-addressed when
|
|
204
|
+
``version`` is given) and writes every served file under
|
|
205
|
+
``destination``, creating parent directories. The written files are
|
|
206
|
+
exactly the served bytes; the pulled version and file list are
|
|
207
|
+
recorded in a ``.reef-harness-version`` json sidecar beside the tree
|
|
208
|
+
(client-side bookkeeping, not part of the served tree). A repeat
|
|
209
|
+
pull into the same destination first removes the files the previous
|
|
210
|
+
pull recorded, so pulling an older version never leaves a newer
|
|
211
|
+
version's files behind. Served paths must stay inside the
|
|
212
|
+
destination; an absolute or parent-escaping path refuses the pull.
|
|
213
|
+
No rendering, no validation: the service serves native files and
|
|
214
|
+
this method only writes them.
|
|
215
|
+
"""
|
|
216
|
+
path = "/reef/harness"
|
|
217
|
+
if version is not None:
|
|
218
|
+
path += f"?version={urllib.parse.quote(version, safe='')}"
|
|
219
|
+
headers = {"x-reef-scenario": scenario}
|
|
220
|
+
covered = {name.lower() for name in headers}
|
|
221
|
+
headers.update({name: value for name, value in (extra_headers or {}).items() if name.lower() not in covered})
|
|
222
|
+
manifest = self.get(path, extra_headers=headers)
|
|
223
|
+
files = manifest.get("files", {})
|
|
224
|
+
for relative in files:
|
|
225
|
+
parts = PurePosixPath(relative).parts
|
|
226
|
+
if PurePosixPath(relative).is_absolute() or ".." in parts:
|
|
227
|
+
raise ValueError(f"served path {relative!r} escapes the destination")
|
|
228
|
+
root = Path(destination)
|
|
229
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
230
|
+
sidecar = root / HARNESS_VERSION_SIDECAR
|
|
231
|
+
if sidecar.is_file():
|
|
232
|
+
try:
|
|
233
|
+
previous = json.loads(sidecar.read_text(encoding="utf-8"))
|
|
234
|
+
except json.JSONDecodeError:
|
|
235
|
+
previous = {}
|
|
236
|
+
for relative in previous.get("files", ()):
|
|
237
|
+
if relative not in files:
|
|
238
|
+
stale = root / relative
|
|
239
|
+
if stale.is_file():
|
|
240
|
+
stale.unlink()
|
|
241
|
+
for relative, content in files.items():
|
|
242
|
+
target = root / relative
|
|
243
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
244
|
+
with open(target, "w", encoding="utf-8", newline="") as handle:
|
|
245
|
+
handle.write(content)
|
|
246
|
+
pulled = str(manifest["artifact_version"])
|
|
247
|
+
record = {"artifact_version": pulled, "files": sorted(files)}
|
|
248
|
+
sidecar.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
|
|
249
|
+
return pulled
|
|
250
|
+
|
|
251
|
+
def _post(
|
|
252
|
+
self,
|
|
253
|
+
path: str,
|
|
254
|
+
scenario: str,
|
|
255
|
+
payload: Mapping[str, Any],
|
|
256
|
+
*,
|
|
257
|
+
recipe: str | None = None,
|
|
258
|
+
artifact_version: str | None = None,
|
|
259
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
260
|
+
) -> dict[str, Any]:
|
|
261
|
+
body, _ = self._post_with_headers(
|
|
262
|
+
path,
|
|
263
|
+
scenario,
|
|
264
|
+
payload,
|
|
265
|
+
recipe=recipe,
|
|
266
|
+
artifact_version=artifact_version,
|
|
267
|
+
extra_headers=extra_headers,
|
|
268
|
+
)
|
|
269
|
+
return body
|
|
270
|
+
|
|
271
|
+
def _post_with_headers(
|
|
272
|
+
self,
|
|
273
|
+
path: str,
|
|
274
|
+
scenario: str,
|
|
275
|
+
payload: Mapping[str, Any],
|
|
276
|
+
*,
|
|
277
|
+
recipe: str | None = None,
|
|
278
|
+
artifact_version: str | None = None,
|
|
279
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
280
|
+
) -> tuple[dict[str, Any], Mapping[str, str]]:
|
|
281
|
+
# Explicit arguments own the protocol headers; extra_headers only fill
|
|
282
|
+
# in what the arguments do not cover (scenario/recipe overrides must
|
|
283
|
+
# therefore be resolved by the caller before dispatch).
|
|
284
|
+
headers = {
|
|
285
|
+
"Content-Type": "application/json",
|
|
286
|
+
"x-reef-scenario": scenario,
|
|
287
|
+
}
|
|
288
|
+
if self.token:
|
|
289
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
290
|
+
if recipe:
|
|
291
|
+
headers["x-reef-recipe"] = recipe
|
|
292
|
+
if artifact_version:
|
|
293
|
+
headers["x-reef-artifact-version"] = artifact_version
|
|
294
|
+
covered = {name.lower() for name in headers}
|
|
295
|
+
headers.update({name: value for name, value in (extra_headers or {}).items() if name.lower() not in covered})
|
|
296
|
+
request = urllib.request.Request(
|
|
297
|
+
f"{self.service_url}{path}",
|
|
298
|
+
data=json.dumps(dict(payload)).encode(),
|
|
299
|
+
headers=headers,
|
|
300
|
+
method="POST",
|
|
301
|
+
)
|
|
302
|
+
try:
|
|
303
|
+
with urllib.request.urlopen(request, timeout=self.timeout_s) as response:
|
|
304
|
+
body = response.read().decode()
|
|
305
|
+
response_headers = dict(getattr(response, "headers", {}).items())
|
|
306
|
+
except urllib.error.HTTPError as exc:
|
|
307
|
+
body = exc.read().decode(errors="replace")
|
|
308
|
+
raise ReefClientError(exc.code, body, exc.headers.get("Content-Type")) from exc
|
|
309
|
+
return (json.loads(body) if body else {}), {key.lower(): value for key, value in response_headers.items()}
|
reef_client/serve.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
"""Serve mode: a local sidecar that agents treat as their model endpoint.
|
|
2
|
+
|
|
3
|
+
Agents point their OpenAI-compatible ``base_url`` here and stay
|
|
4
|
+
reef-oblivious; the sidecar owns the bookkeeping scenarios otherwise
|
|
5
|
+
re-implement per example (see ``examples/openclawrl/personal/stamp_proxy.py``
|
|
6
|
+
for the hand-rolled version this subsumes):
|
|
7
|
+
|
|
8
|
+
* **Session stamping** — the harness declares the session boundary out of
|
|
9
|
+
band; the sidecar stamps it onto forwarded calls matching a predicate.
|
|
10
|
+
* **Trajectory capture** — chat completions are recorded (request, response,
|
|
11
|
+
reef receipt) into a bounded in-memory store, drainable over HTTP.
|
|
12
|
+
* **SSE in both directions** — upstream streams pass through chunk by chunk
|
|
13
|
+
while an accumulator rebuilds the completion for capture; with
|
|
14
|
+
``force_non_stream`` the upstream call is buffered and the completion is
|
|
15
|
+
re-synthesized as a stream for clients that asked for one.
|
|
16
|
+
|
|
17
|
+
python -m reef_client.serve --listen 29100 --upstream http://127.0.0.1:29000
|
|
18
|
+
|
|
19
|
+
Control endpoints (never forwarded):
|
|
20
|
+
|
|
21
|
+
POST /_session {"id": "..."} declare one global session boundary
|
|
22
|
+
(legacy mode: bare paths ride it;
|
|
23
|
+
sequential sessions only)
|
|
24
|
+
POST /_sessions {"id": "..."} create an addressable session: the
|
|
25
|
+
response ``url`` (a ``/s/{id}`` prefix)
|
|
26
|
+
is the agent's base_url root, so
|
|
27
|
+
concurrent sessions self-identify by
|
|
28
|
+
path and never share state
|
|
29
|
+
GET /_sessions list addressable session ids
|
|
30
|
+
DELETE /_sessions/{id} close a session
|
|
31
|
+
GET /_captures snapshot captured turns as JSON
|
|
32
|
+
GET /_sessions/{id}/captures snapshot one session's turns
|
|
33
|
+
DELETE /_captures clear the capture store
|
|
34
|
+
|
|
35
|
+
Everything else is forwarded to upstream. A ``/s/{id}/...`` path has the
|
|
36
|
+
prefix stripped before forwarding, and the stamped session is the routed id.
|
|
37
|
+
With no prefix the stamped session is the globally declared one, so agents
|
|
38
|
+
whose base_url is fixed (e.g. a static config file) keep working unchanged.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import argparse
|
|
44
|
+
import contextlib
|
|
45
|
+
import http.client
|
|
46
|
+
import json
|
|
47
|
+
import re
|
|
48
|
+
import threading
|
|
49
|
+
import time
|
|
50
|
+
from collections import deque
|
|
51
|
+
from collections.abc import Callable, Mapping
|
|
52
|
+
from dataclasses import asdict, dataclass, field
|
|
53
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
54
|
+
from typing import Any
|
|
55
|
+
from urllib.parse import urlsplit
|
|
56
|
+
|
|
57
|
+
from reef_client.sse import SSEAccumulator, synthesize_sse_events
|
|
58
|
+
|
|
59
|
+
_HOP_BY_HOP = {
|
|
60
|
+
"connection",
|
|
61
|
+
"keep-alive",
|
|
62
|
+
"proxy-authenticate",
|
|
63
|
+
"proxy-authorization",
|
|
64
|
+
"te",
|
|
65
|
+
"trailers",
|
|
66
|
+
"transfer-encoding",
|
|
67
|
+
"upgrade",
|
|
68
|
+
"host",
|
|
69
|
+
"content-length", # always recomputed for the forwarded body
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
RECEIPT_HEADER = "x-reef-agent-data-id"
|
|
73
|
+
|
|
74
|
+
SESSION_PREFIX = "/s/"
|
|
75
|
+
_SESSION_ID_RE = re.compile(r"[A-Za-z0-9._~-]+")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def has_tools(body: dict[str, Any] | None) -> bool:
|
|
79
|
+
"""Main-loop heuristic: agent-loop calls carry tool definitions; harness
|
|
80
|
+
side tasks (title generation, compression summaries, ...) share the
|
|
81
|
+
endpoint but must not register as turns."""
|
|
82
|
+
return bool(body) and "tools" in body
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class CapturedTurn:
|
|
87
|
+
session_id: str
|
|
88
|
+
path: str
|
|
89
|
+
status: int
|
|
90
|
+
request: dict[str, Any] | None
|
|
91
|
+
response: dict[str, Any] | None
|
|
92
|
+
receipt: str | None
|
|
93
|
+
client_stream: bool
|
|
94
|
+
duration_s: float
|
|
95
|
+
at: float = field(default_factory=time.time)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class CaptureStore:
|
|
99
|
+
"""Thread-safe bounded store of captured turns."""
|
|
100
|
+
|
|
101
|
+
def __init__(self, limit: int = 10000) -> None:
|
|
102
|
+
self._turns: deque[CapturedTurn] = deque(maxlen=limit)
|
|
103
|
+
self._lock = threading.Lock()
|
|
104
|
+
|
|
105
|
+
def add(self, turn: CapturedTurn) -> None:
|
|
106
|
+
with self._lock:
|
|
107
|
+
self._turns.append(turn)
|
|
108
|
+
|
|
109
|
+
def snapshot(self, session_id: str | None = None) -> list[dict[str, Any]]:
|
|
110
|
+
with self._lock:
|
|
111
|
+
return [asdict(turn) for turn in self._turns if session_id is None or turn.session_id == session_id]
|
|
112
|
+
|
|
113
|
+
def clear(self) -> int:
|
|
114
|
+
with self._lock:
|
|
115
|
+
count = len(self._turns)
|
|
116
|
+
self._turns.clear()
|
|
117
|
+
return count
|
|
118
|
+
|
|
119
|
+
def __len__(self) -> int:
|
|
120
|
+
with self._lock:
|
|
121
|
+
return len(self._turns)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class SessionRegistry:
|
|
125
|
+
"""Addressable sessions: each registered id owns a ``/s/{id}`` URL prefix."""
|
|
126
|
+
|
|
127
|
+
def __init__(self) -> None:
|
|
128
|
+
self._created: dict[str, float] = {}
|
|
129
|
+
self._lock = threading.Lock()
|
|
130
|
+
|
|
131
|
+
def create(self, session_id: str) -> None:
|
|
132
|
+
with self._lock:
|
|
133
|
+
self._created.setdefault(session_id, time.time())
|
|
134
|
+
|
|
135
|
+
def __contains__(self, session_id: str) -> bool:
|
|
136
|
+
with self._lock:
|
|
137
|
+
return session_id in self._created
|
|
138
|
+
|
|
139
|
+
def delete(self, session_id: str) -> bool:
|
|
140
|
+
with self._lock:
|
|
141
|
+
return self._created.pop(session_id, None) is not None
|
|
142
|
+
|
|
143
|
+
def list(self) -> list[str]:
|
|
144
|
+
with self._lock:
|
|
145
|
+
return sorted(self._created)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass
|
|
149
|
+
class ServeConfig:
|
|
150
|
+
upstream: str
|
|
151
|
+
listen_host: str = "127.0.0.1"
|
|
152
|
+
listen_port: int = 29100
|
|
153
|
+
# Session stamping: when a session is declared, stamp this header onto
|
|
154
|
+
# forwarded calls for which ``stamp_when(body, method)`` is true.
|
|
155
|
+
session_header: str | None = None
|
|
156
|
+
stamp_when: Callable[[dict[str, Any] | None, str], bool] = lambda body, method: method == "POST"
|
|
157
|
+
# Static headers added to every forwarded call (client-sent values win):
|
|
158
|
+
# e.g. reef's x-reef-scenario / authorization when fronting reef directly.
|
|
159
|
+
extra_headers: Mapping[str, str] = field(default_factory=dict)
|
|
160
|
+
# Static headers that REPLACE client-sent values. OpenAI-compatible
|
|
161
|
+
# clients always send their own ``Authorization: Bearer <api_key>``, so a
|
|
162
|
+
# shim that owns the upstream's auth must override, never setdefault.
|
|
163
|
+
override_headers: Mapping[str, str] = field(default_factory=dict)
|
|
164
|
+
# Buffer upstream calls (strip stream/stream_options) and re-synthesize
|
|
165
|
+
# SSE for streaming clients — required when the upstream needs the
|
|
166
|
+
# complete response for capture (e.g. reef's training block).
|
|
167
|
+
force_non_stream: bool = False
|
|
168
|
+
capture_paths: tuple[str, ...] = ("/v1/chat/completions",)
|
|
169
|
+
capture_limit: int = 10000
|
|
170
|
+
timeout_s: float = 7200.0
|
|
171
|
+
|
|
172
|
+
def __post_init__(self) -> None:
|
|
173
|
+
if not self.upstream:
|
|
174
|
+
raise ValueError("upstream must be non-empty")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def build_handler(config: ServeConfig, store: CaptureStore) -> type[BaseHTTPRequestHandler]:
|
|
178
|
+
parsed = urlsplit(config.upstream)
|
|
179
|
+
state: dict[str, str] = {"session_id": ""}
|
|
180
|
+
registry = SessionRegistry()
|
|
181
|
+
lock = threading.Lock()
|
|
182
|
+
|
|
183
|
+
class Handler(BaseHTTPRequestHandler):
|
|
184
|
+
protocol_version = "HTTP/1.1"
|
|
185
|
+
|
|
186
|
+
def log_message(self, fmt: str, *args: Any) -> None: # quiet
|
|
187
|
+
pass
|
|
188
|
+
|
|
189
|
+
def _reply_json(self, status: int, payload: dict[str, Any]) -> None:
|
|
190
|
+
body = json.dumps(payload).encode()
|
|
191
|
+
self.send_response(status)
|
|
192
|
+
self.send_header("Content-Type", "application/json")
|
|
193
|
+
self.send_header("Content-Length", str(len(body)))
|
|
194
|
+
self.end_headers()
|
|
195
|
+
self.wfile.write(body)
|
|
196
|
+
|
|
197
|
+
def _route(self) -> tuple[str, str | None]:
|
|
198
|
+
"""Split the request target into (forward_path, routed session id)."""
|
|
199
|
+
split = urlsplit(self.path)
|
|
200
|
+
path = split.path
|
|
201
|
+
session_id = None
|
|
202
|
+
if path.startswith(SESSION_PREFIX):
|
|
203
|
+
session_id, _, remainder = path[len(SESSION_PREFIX) :].partition("/")
|
|
204
|
+
path = "/" + remainder
|
|
205
|
+
if split.query:
|
|
206
|
+
path += f"?{split.query}"
|
|
207
|
+
return path, session_id or None
|
|
208
|
+
|
|
209
|
+
def _dispatch(self) -> None:
|
|
210
|
+
forward_path, routed = self._route()
|
|
211
|
+
if routed is not None and routed not in registry:
|
|
212
|
+
self._send_error_json(404, f"unknown session {routed!r}; POST /_sessions first")
|
|
213
|
+
return
|
|
214
|
+
self._forward(forward_path, routed)
|
|
215
|
+
|
|
216
|
+
def do_POST(self) -> None:
|
|
217
|
+
if self.path == "/_session":
|
|
218
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
219
|
+
body = json.loads(self.rfile.read(length) or b"{}")
|
|
220
|
+
with lock:
|
|
221
|
+
state["session_id"] = str(body.get("id", ""))
|
|
222
|
+
self._reply_json(200, {"ok": True, "id": state["session_id"]})
|
|
223
|
+
return
|
|
224
|
+
if self.path == "/_sessions":
|
|
225
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
226
|
+
body = json.loads(self.rfile.read(length) or b"{}")
|
|
227
|
+
session_id = str(body.get("id", "")).strip()
|
|
228
|
+
if not _SESSION_ID_RE.fullmatch(session_id):
|
|
229
|
+
self._reply_json(400, {"error": {"message": "id must match [A-Za-z0-9._~-]+"}})
|
|
230
|
+
return
|
|
231
|
+
registry.create(session_id)
|
|
232
|
+
host = self.headers.get("Host", f"{config.listen_host}:{config.listen_port}")
|
|
233
|
+
path = f"{SESSION_PREFIX}{session_id}"
|
|
234
|
+
self._reply_json(200, {"id": session_id, "path": path, "url": f"http://{host}{path}"})
|
|
235
|
+
return
|
|
236
|
+
self._dispatch()
|
|
237
|
+
|
|
238
|
+
def do_GET(self) -> None:
|
|
239
|
+
if self.path == "/_captures":
|
|
240
|
+
self._reply_json(200, {"turns": store.snapshot()})
|
|
241
|
+
return
|
|
242
|
+
if self.path == "/_sessions":
|
|
243
|
+
self._reply_json(200, {"sessions": registry.list()})
|
|
244
|
+
return
|
|
245
|
+
if self.path.startswith("/_sessions/") and self.path.endswith("/captures"):
|
|
246
|
+
session_id = self.path[len("/_sessions/") : -len("/captures")]
|
|
247
|
+
self._reply_json(200, {"turns": store.snapshot(session_id)})
|
|
248
|
+
return
|
|
249
|
+
self._dispatch()
|
|
250
|
+
|
|
251
|
+
def do_DELETE(self) -> None:
|
|
252
|
+
if self.path == "/_captures":
|
|
253
|
+
self._reply_json(200, {"cleared": store.clear()})
|
|
254
|
+
return
|
|
255
|
+
if self.path.startswith("/_sessions/"):
|
|
256
|
+
session_id = self.path[len("/_sessions/") :]
|
|
257
|
+
if registry.delete(session_id):
|
|
258
|
+
self._reply_json(200, {"deleted": session_id})
|
|
259
|
+
else:
|
|
260
|
+
self._reply_json(404, {"error": {"message": f"unknown session {session_id!r}"}})
|
|
261
|
+
return
|
|
262
|
+
self._send_error_json(404, "unknown control endpoint")
|
|
263
|
+
|
|
264
|
+
def _send_error_json(self, status: int, message: str) -> None:
|
|
265
|
+
with contextlib.suppress(Exception):
|
|
266
|
+
self._reply_json(status, {"error": {"message": message}})
|
|
267
|
+
|
|
268
|
+
def _write_chunk(self, data: bytes) -> None:
|
|
269
|
+
self.wfile.write(f"{len(data):X}\r\n".encode() + data + b"\r\n")
|
|
270
|
+
self.wfile.flush()
|
|
271
|
+
|
|
272
|
+
def _forward(self, forward_path: str, routed_session: str | None) -> None:
|
|
273
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
274
|
+
raw = self.rfile.read(length) if length else None
|
|
275
|
+
body_json: dict[str, Any] | None = None
|
|
276
|
+
if raw:
|
|
277
|
+
try:
|
|
278
|
+
body_json = json.loads(raw)
|
|
279
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
280
|
+
body_json = None
|
|
281
|
+
|
|
282
|
+
client_stream = bool(body_json and body_json.get("stream") is True)
|
|
283
|
+
include_usage = bool(body_json and (body_json.get("stream_options") or {}).get("include_usage"))
|
|
284
|
+
|
|
285
|
+
forward_body = raw
|
|
286
|
+
if body_json is not None and config.force_non_stream:
|
|
287
|
+
stripped = {key: value for key, value in body_json.items() if key not in ("stream", "stream_options")}
|
|
288
|
+
forward_body = json.dumps(stripped).encode()
|
|
289
|
+
|
|
290
|
+
headers = {key: value for key, value in self.headers.items() if key.lower() not in _HOP_BY_HOP}
|
|
291
|
+
with lock:
|
|
292
|
+
declared = state["session_id"]
|
|
293
|
+
session_id = routed_session if routed_session is not None else declared
|
|
294
|
+
stamped = ""
|
|
295
|
+
if session_id and config.session_header and config.stamp_when(body_json, self.command):
|
|
296
|
+
headers.setdefault(config.session_header, session_id)
|
|
297
|
+
stamped = session_id
|
|
298
|
+
for name, value in config.extra_headers.items():
|
|
299
|
+
headers.setdefault(name, value)
|
|
300
|
+
if config.override_headers:
|
|
301
|
+
headers = {
|
|
302
|
+
name: value
|
|
303
|
+
for name, value in headers.items()
|
|
304
|
+
if name.lower() not in {key.lower() for key in config.override_headers}
|
|
305
|
+
}
|
|
306
|
+
headers.update(config.override_headers)
|
|
307
|
+
if forward_body is not None:
|
|
308
|
+
headers["Content-Length"] = str(len(forward_body))
|
|
309
|
+
|
|
310
|
+
conn = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=config.timeout_s)
|
|
311
|
+
started = time.monotonic()
|
|
312
|
+
try:
|
|
313
|
+
conn.request(self.command, forward_path, body=forward_body, headers=headers)
|
|
314
|
+
response = conn.getresponse()
|
|
315
|
+
except Exception as exc:
|
|
316
|
+
self._send_error_json(502, f"reef-client serve: {exc}")
|
|
317
|
+
conn.close()
|
|
318
|
+
return
|
|
319
|
+
|
|
320
|
+
try:
|
|
321
|
+
self._relay(response, forward_path, body_json, stamped, client_stream, include_usage, started)
|
|
322
|
+
finally:
|
|
323
|
+
conn.close()
|
|
324
|
+
|
|
325
|
+
def _relay(
|
|
326
|
+
self,
|
|
327
|
+
response: http.client.HTTPResponse,
|
|
328
|
+
forward_path: str,
|
|
329
|
+
request_json: dict[str, Any] | None,
|
|
330
|
+
session_id: str,
|
|
331
|
+
client_stream: bool,
|
|
332
|
+
include_usage: bool,
|
|
333
|
+
started: float,
|
|
334
|
+
) -> None:
|
|
335
|
+
response_headers = {key.lower(): value for key, value in response.getheaders()}
|
|
336
|
+
receipt = response_headers.get(RECEIPT_HEADER)
|
|
337
|
+
is_sse = "text/event-stream" in response_headers.get("content-type", "")
|
|
338
|
+
capture = forward_path in config.capture_paths and request_json is not None
|
|
339
|
+
|
|
340
|
+
if is_sse:
|
|
341
|
+
accumulator = self._relay_stream(response, receipt)
|
|
342
|
+
if capture:
|
|
343
|
+
store.add(
|
|
344
|
+
CapturedTurn(
|
|
345
|
+
session_id,
|
|
346
|
+
forward_path,
|
|
347
|
+
response.status,
|
|
348
|
+
request_json,
|
|
349
|
+
accumulator.completion,
|
|
350
|
+
receipt,
|
|
351
|
+
client_stream,
|
|
352
|
+
time.monotonic() - started,
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
self.wfile.write(b"0\r\n\r\n")
|
|
356
|
+
return
|
|
357
|
+
|
|
358
|
+
payload = response.read()
|
|
359
|
+
duration = time.monotonic() - started
|
|
360
|
+
completion: dict[str, Any] | None = None
|
|
361
|
+
try:
|
|
362
|
+
completion = json.loads(payload)
|
|
363
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
364
|
+
completion = None
|
|
365
|
+
if capture:
|
|
366
|
+
store.add(
|
|
367
|
+
CapturedTurn(
|
|
368
|
+
session_id,
|
|
369
|
+
forward_path,
|
|
370
|
+
response.status,
|
|
371
|
+
request_json,
|
|
372
|
+
completion,
|
|
373
|
+
receipt,
|
|
374
|
+
client_stream,
|
|
375
|
+
duration,
|
|
376
|
+
)
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
if not client_stream or response.status >= 400:
|
|
380
|
+
# Buffered relay; upstream errors keep their status verbatim.
|
|
381
|
+
self.send_response(response.status)
|
|
382
|
+
for key, value in response.getheaders():
|
|
383
|
+
if key.lower() in _HOP_BY_HOP:
|
|
384
|
+
continue
|
|
385
|
+
self.send_header(key, value)
|
|
386
|
+
self.send_header("Content-Length", str(len(payload)))
|
|
387
|
+
self.end_headers()
|
|
388
|
+
self.wfile.write(payload)
|
|
389
|
+
return
|
|
390
|
+
|
|
391
|
+
# The client asked for a stream but the upstream answered a
|
|
392
|
+
# buffered completion (force_non_stream): re-synthesize SSE.
|
|
393
|
+
if completion is None:
|
|
394
|
+
self._send_error_json(502, "reef-client serve: upstream returned non-JSON for a streaming request")
|
|
395
|
+
return
|
|
396
|
+
self.send_response(200)
|
|
397
|
+
if receipt:
|
|
398
|
+
self.send_header(RECEIPT_HEADER, receipt)
|
|
399
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
400
|
+
self.send_header("Cache-Control", "no-cache")
|
|
401
|
+
self.send_header("Transfer-Encoding", "chunked")
|
|
402
|
+
self.end_headers()
|
|
403
|
+
for event in synthesize_sse_events(completion, include_usage=include_usage):
|
|
404
|
+
self._write_chunk(event.encode())
|
|
405
|
+
self.wfile.write(b"0\r\n\r\n")
|
|
406
|
+
|
|
407
|
+
def _relay_stream(self, response: http.client.HTTPResponse, receipt: str | None) -> SSEAccumulator:
|
|
408
|
+
self.send_response(response.status)
|
|
409
|
+
for key, value in response.getheaders():
|
|
410
|
+
if key.lower() in _HOP_BY_HOP:
|
|
411
|
+
continue
|
|
412
|
+
self.send_header(key, value)
|
|
413
|
+
self.send_header("Transfer-Encoding", "chunked")
|
|
414
|
+
self.end_headers()
|
|
415
|
+
|
|
416
|
+
accumulator = SSEAccumulator()
|
|
417
|
+
while True:
|
|
418
|
+
chunk = response.read(16384)
|
|
419
|
+
if not chunk:
|
|
420
|
+
break
|
|
421
|
+
accumulator.feed(chunk)
|
|
422
|
+
self._write_chunk(chunk)
|
|
423
|
+
accumulator.finish()
|
|
424
|
+
return accumulator
|
|
425
|
+
|
|
426
|
+
return Handler
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def run(config: ServeConfig, store: CaptureStore | None = None) -> None:
|
|
430
|
+
store = store or CaptureStore(config.capture_limit)
|
|
431
|
+
server = ThreadingHTTPServer((config.listen_host, config.listen_port), build_handler(config, store))
|
|
432
|
+
print(
|
|
433
|
+
f"reef-client serve listening on {config.listen_host}:{config.listen_port} -> {config.upstream}",
|
|
434
|
+
flush=True,
|
|
435
|
+
)
|
|
436
|
+
server.serve_forever()
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def main() -> None:
|
|
440
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
441
|
+
parser.add_argument("--listen", type=int, default=29100)
|
|
442
|
+
parser.add_argument("--host", default="127.0.0.1")
|
|
443
|
+
parser.add_argument("--upstream", default="http://127.0.0.1:29000")
|
|
444
|
+
parser.add_argument("--session-header", default=None, help="header stamped with the declared session id")
|
|
445
|
+
parser.add_argument(
|
|
446
|
+
"--stamp-tools-only",
|
|
447
|
+
action="store_true",
|
|
448
|
+
help="stamp only main agent-loop calls (requests carrying tool definitions)",
|
|
449
|
+
)
|
|
450
|
+
parser.add_argument("--force-non-stream", action="store_true", help="buffer upstream; synthesize SSE for clients")
|
|
451
|
+
parser.add_argument("--no-capture", action="store_true", help="disable trajectory capture")
|
|
452
|
+
parser.add_argument("--timeout", type=float, default=7200.0)
|
|
453
|
+
args = parser.parse_args()
|
|
454
|
+
|
|
455
|
+
stamp_when = None
|
|
456
|
+
if args.stamp_tools_only:
|
|
457
|
+
stamp_when = lambda body, method: method == "POST" and has_tools(body) # noqa: E731
|
|
458
|
+
config = ServeConfig(
|
|
459
|
+
upstream=args.upstream,
|
|
460
|
+
listen_host=args.host,
|
|
461
|
+
listen_port=args.listen,
|
|
462
|
+
session_header=args.session_header,
|
|
463
|
+
**({"stamp_when": stamp_when} if stamp_when else {}),
|
|
464
|
+
force_non_stream=args.force_non_stream,
|
|
465
|
+
capture_paths=() if args.no_capture else ("/v1/chat/completions",),
|
|
466
|
+
timeout_s=args.timeout,
|
|
467
|
+
)
|
|
468
|
+
run(config)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
if __name__ == "__main__":
|
|
472
|
+
main()
|
reef_client/skill.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Fetch the served skill file from a running Reef.
|
|
2
|
+
|
|
3
|
+
The skill component of the ``reef_client`` SDK, standard library only. It
|
|
4
|
+
reads the scenario's harness manifest (``GET /reef/harness``), extracts
|
|
5
|
+
``skills/SKILL.md``, and can write it to a local path only when the content
|
|
6
|
+
changed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import urllib.request
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
SKILL_PATH = "skills/SKILL.md"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SkillNotServedError(RuntimeError):
|
|
19
|
+
"""The scenario's harness manifest serves no ``skills/SKILL.md``."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def fetch_skill(url: str, scenario: str, token: str | None = None) -> tuple[str, str]:
|
|
23
|
+
"""Return (skill text, version) from the scenario's harness manifest."""
|
|
24
|
+
headers = {"x-reef-scenario": scenario}
|
|
25
|
+
if token:
|
|
26
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
27
|
+
request = urllib.request.Request(f"{url.rstrip('/')}/reef/harness", headers=headers)
|
|
28
|
+
with urllib.request.urlopen(request, timeout=30) as response:
|
|
29
|
+
manifest = json.loads(response.read().decode("utf-8"))
|
|
30
|
+
text = manifest.get("files", {}).get(SKILL_PATH)
|
|
31
|
+
if text is None:
|
|
32
|
+
raise SkillNotServedError(f"scenario {scenario!r} serves no {SKILL_PATH}")
|
|
33
|
+
return text, manifest.get("artifact_version", "")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sync_skill(url: str, scenario: str, out: Path, token: str | None = None) -> tuple[str, bool]:
|
|
37
|
+
"""Fetch and write the skill to ``out``; returns (version, changed)."""
|
|
38
|
+
text, version = fetch_skill(url, scenario, token)
|
|
39
|
+
if out.exists() and out.read_text(encoding="utf-8") == text:
|
|
40
|
+
return version, False
|
|
41
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
out.write_text(text, encoding="utf-8")
|
|
43
|
+
return version, True
|
reef_client/sse.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""OpenAI-style SSE helpers, shared by the serve mode and graders.
|
|
2
|
+
|
|
3
|
+
Two directions, both stdlib-only:
|
|
4
|
+
|
|
5
|
+
* ``synthesize_sse_events`` re-emits one buffered chat completion as
|
|
6
|
+
``chat.completion.chunk`` events. Training capture forces non-streaming
|
|
7
|
+
upstream (the complete response is needed for trajectory capture), but
|
|
8
|
+
streaming clients must still receive a protocol-valid stream.
|
|
9
|
+
* ``SSEAccumulator`` does the inverse: it consumes a live
|
|
10
|
+
``chat.completion.chunk`` stream and rebuilds the buffered completion,
|
|
11
|
+
so a passthrough proxy can capture trajectories without delaying the
|
|
12
|
+
client-facing stream.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import codecs
|
|
18
|
+
import json
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def synthesize_sse_events(payload: dict[str, Any], *, include_usage: bool = False) -> list[str]:
|
|
23
|
+
"""Re-emit one buffered chat completion as OpenAI stream events.
|
|
24
|
+
|
|
25
|
+
Content and tool calls each arrive as a single delta rather than
|
|
26
|
+
token-by-token; client SDKs treat delta granularity as an implementation
|
|
27
|
+
detail, so one large delta is protocol-valid.
|
|
28
|
+
"""
|
|
29
|
+
base = {
|
|
30
|
+
"id": payload.get("id", "chatcmpl-reef-client"),
|
|
31
|
+
"object": "chat.completion.chunk",
|
|
32
|
+
"created": payload.get("created", 0),
|
|
33
|
+
"model": payload.get("model", ""),
|
|
34
|
+
}
|
|
35
|
+
events: list[str] = []
|
|
36
|
+
|
|
37
|
+
def emit(delta: dict[str, Any], index: int, finish_reason: str | None = None) -> None:
|
|
38
|
+
chunk = {**base, "choices": [{"index": index, "delta": delta, "finish_reason": finish_reason}]}
|
|
39
|
+
events.append(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n")
|
|
40
|
+
|
|
41
|
+
for index, choice in enumerate(payload.get("choices", [])):
|
|
42
|
+
message = choice.get("message") or {}
|
|
43
|
+
emit({"role": message.get("role", "assistant")}, index)
|
|
44
|
+
content = message.get("content")
|
|
45
|
+
if content:
|
|
46
|
+
emit({"content": content}, index)
|
|
47
|
+
for call_index, call in enumerate(message.get("tool_calls") or []):
|
|
48
|
+
function = call.get("function") or {}
|
|
49
|
+
emit(
|
|
50
|
+
{
|
|
51
|
+
"tool_calls": [
|
|
52
|
+
{
|
|
53
|
+
"index": call_index,
|
|
54
|
+
"id": call.get("id"),
|
|
55
|
+
"type": call.get("type", "function"),
|
|
56
|
+
"function": {
|
|
57
|
+
"name": function.get("name"),
|
|
58
|
+
"arguments": function.get("arguments", ""),
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
},
|
|
63
|
+
index,
|
|
64
|
+
)
|
|
65
|
+
emit({}, index, finish_reason=choice.get("finish_reason", "stop"))
|
|
66
|
+
|
|
67
|
+
if include_usage and payload.get("usage") is not None:
|
|
68
|
+
events.append(
|
|
69
|
+
f"data: {json.dumps({**base, 'choices': [], 'usage': payload['usage']}, ensure_ascii=False)}\n\n"
|
|
70
|
+
)
|
|
71
|
+
events.append("data: [DONE]\n\n")
|
|
72
|
+
return events
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class SSEAccumulator:
|
|
76
|
+
"""Rebuild a buffered chat completion from a chunk stream.
|
|
77
|
+
|
|
78
|
+
Feed raw response bytes as they arrive; ``completion`` then returns a
|
|
79
|
+
dict shaped like a non-streaming chat completion. Delta concatenation
|
|
80
|
+
follows OpenAI semantics: content and tool-call arguments accumulate by
|
|
81
|
+
(choice index, tool-call index), scalar fields keep their first value.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(self) -> None:
|
|
85
|
+
self._decoder = codecs.getincrementaldecoder("utf-8")()
|
|
86
|
+
self._buffer = ""
|
|
87
|
+
self.done = False
|
|
88
|
+
self.id = ""
|
|
89
|
+
self.model = ""
|
|
90
|
+
self.created = 0
|
|
91
|
+
self.usage: dict[str, Any] | None = None
|
|
92
|
+
self._choices: dict[int, dict[str, Any]] = {}
|
|
93
|
+
|
|
94
|
+
def feed(self, data: bytes) -> None:
|
|
95
|
+
self._buffer += self._decoder.decode(data)
|
|
96
|
+
while "\n" in self._buffer:
|
|
97
|
+
line, self._buffer = self._buffer.split("\n", 1)
|
|
98
|
+
self._handle_line(line.strip())
|
|
99
|
+
|
|
100
|
+
def finish(self) -> None:
|
|
101
|
+
"""Flush any trailing bytes once the response is exhausted."""
|
|
102
|
+
tail = self._buffer + self._decoder.decode(b"", final=True)
|
|
103
|
+
self._buffer = ""
|
|
104
|
+
if tail.strip():
|
|
105
|
+
self._handle_line(tail.strip())
|
|
106
|
+
|
|
107
|
+
def _handle_line(self, line: str) -> None:
|
|
108
|
+
if not line or line.startswith(":") or not line.startswith("data:"):
|
|
109
|
+
return # blank separator, keepalive comment, or event:/id: field
|
|
110
|
+
data = line[len("data:") :].strip()
|
|
111
|
+
if data == "[DONE]":
|
|
112
|
+
self.done = True
|
|
113
|
+
return
|
|
114
|
+
self._apply_chunk(json.loads(data))
|
|
115
|
+
|
|
116
|
+
def _apply_chunk(self, chunk: dict[str, Any]) -> None:
|
|
117
|
+
self.id = chunk.get("id") or self.id
|
|
118
|
+
self.model = chunk.get("model") or self.model
|
|
119
|
+
self.created = chunk.get("created") or self.created
|
|
120
|
+
if chunk.get("usage") is not None:
|
|
121
|
+
self.usage = chunk["usage"]
|
|
122
|
+
for choice in chunk.get("choices") or []:
|
|
123
|
+
index = choice.get("index", 0)
|
|
124
|
+
slot = self._choices.setdefault(
|
|
125
|
+
index, {"role": None, "content": [], "tool_calls": {}, "finish_reason": None}
|
|
126
|
+
)
|
|
127
|
+
delta = choice.get("delta") or {}
|
|
128
|
+
if delta.get("role"):
|
|
129
|
+
slot["role"] = delta["role"]
|
|
130
|
+
if delta.get("content"):
|
|
131
|
+
slot["content"].append(delta["content"])
|
|
132
|
+
for call in delta.get("tool_calls") or []:
|
|
133
|
+
acc = slot["tool_calls"].setdefault(
|
|
134
|
+
call.get("index", 0), {"id": None, "type": None, "name": [], "arguments": []}
|
|
135
|
+
)
|
|
136
|
+
if call.get("id"):
|
|
137
|
+
acc["id"] = call["id"]
|
|
138
|
+
if call.get("type"):
|
|
139
|
+
acc["type"] = call["type"]
|
|
140
|
+
function = call.get("function") or {}
|
|
141
|
+
if function.get("name"):
|
|
142
|
+
acc["name"].append(function["name"])
|
|
143
|
+
if function.get("arguments"):
|
|
144
|
+
acc["arguments"].append(function["arguments"])
|
|
145
|
+
if choice.get("finish_reason"):
|
|
146
|
+
slot["finish_reason"] = choice["finish_reason"]
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def completion(self) -> dict[str, Any] | None:
|
|
150
|
+
"""The accumulated completion, or None if no chunk arrived yet."""
|
|
151
|
+
if not self._choices and self.usage is None:
|
|
152
|
+
return None
|
|
153
|
+
choices = []
|
|
154
|
+
for index in sorted(self._choices):
|
|
155
|
+
slot = self._choices[index]
|
|
156
|
+
message: dict[str, Any] = {
|
|
157
|
+
"role": slot["role"] or "assistant",
|
|
158
|
+
"content": "".join(slot["content"]),
|
|
159
|
+
}
|
|
160
|
+
if slot["tool_calls"]:
|
|
161
|
+
message["tool_calls"] = [
|
|
162
|
+
{
|
|
163
|
+
"id": acc["id"],
|
|
164
|
+
"type": acc["type"] or "function",
|
|
165
|
+
"function": {
|
|
166
|
+
"name": "".join(acc["name"]),
|
|
167
|
+
"arguments": "".join(acc["arguments"]),
|
|
168
|
+
},
|
|
169
|
+
}
|
|
170
|
+
for _, acc in sorted(slot["tool_calls"].items())
|
|
171
|
+
]
|
|
172
|
+
choices.append({"index": index, "message": message, "finish_reason": slot["finish_reason"]})
|
|
173
|
+
completion: dict[str, Any] = {
|
|
174
|
+
"id": self.id,
|
|
175
|
+
"object": "chat.completion",
|
|
176
|
+
"created": self.created,
|
|
177
|
+
"model": self.model,
|
|
178
|
+
"choices": choices,
|
|
179
|
+
}
|
|
180
|
+
if self.usage is not None:
|
|
181
|
+
completion["usage"] = self.usage
|
|
182
|
+
return completion
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: reef-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Stdlib-only client SDK for the Reef protocol
|
|
5
|
+
Author: Human-Agent-Society
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Human-Agent-Society/reef-client
|
|
8
|
+
Project-URL: Repository, https://github.com/Human-Agent-Society/reef-client
|
|
9
|
+
Project-URL: Issues, https://github.com/Human-Agent-Society/reef-client/issues
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# reef_client
|
|
19
|
+
|
|
20
|
+
Stdlib-only client SDK for the Reef protocol. `reef_client` is a client of
|
|
21
|
+
Reef's HTTP wire protocol, not of the `reef` package: it never imports `reef`
|
|
22
|
+
and has no dependencies, so external harnesses can install it or copy it into
|
|
23
|
+
environments that cannot take the `reef` wheel's dependencies.
|
|
24
|
+
|
|
25
|
+
The distribution is `reef-client` ([`pyproject.toml`](pyproject.toml)); the
|
|
26
|
+
import package is the inner [`reef_client/`](reef_client) directory:
|
|
27
|
+
|
|
28
|
+
- [`client.py`](reef_client/client.py) is `ReefClient`, the
|
|
29
|
+
ask/observe/report loop every example shares (see the
|
|
30
|
+
[Reef docs](https://github.com/Human-Agent-Society/reef/blob/main/docs/reference/reef-client.md)),
|
|
31
|
+
plus the harness update channel reads: `harness_versions` (the version
|
|
32
|
+
catalog with gate metrics) and `harness_pull` (write one served tree, head
|
|
33
|
+
or version-addressed, into a directory).
|
|
34
|
+
- [`skill.py`](reef_client/skill.py) fetches and syncs the scenario's served
|
|
35
|
+
skill file (`fetch_skill`/`sync_skill`);
|
|
36
|
+
- [`sse.py`](reef_client/sse.py) converts between buffered chat completions
|
|
37
|
+
and OpenAI-style SSE chunk streams in both directions
|
|
38
|
+
(`synthesize_sse_events` / `SSEAccumulator`).
|
|
39
|
+
- [`serve.py`](reef_client/serve.py) is serve mode: a local sidecar that
|
|
40
|
+
agents treat as their model endpoint (`python -m reef_client.serve`),
|
|
41
|
+
owning session stamping, trajectory capture, receipt collection, and SSE
|
|
42
|
+
passthrough/synthesis so reef-oblivious agents need no SDK. See the
|
|
43
|
+
[reference](https://github.com/Human-Agent-Society/reef/blob/main/docs/reference/reef-client.md#serve-mode-a-local-proxy-for-reef-oblivious-agents).
|
|
44
|
+
|
|
45
|
+
The client and skill helpers are re-exported at the package root:
|
|
46
|
+
`from reef_client import ReefClient, fetch_skill, sync_skill`. Import the
|
|
47
|
+
`sse`/`serve` submodules directly.
|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install reef-client
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
For development:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
git clone https://github.com/Human-Agent-Society/reef-client && cd reef-client
|
|
59
|
+
pip install -e .
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The package is standard library only — copying the inner `reef_client/`
|
|
63
|
+
directory into your harness works too.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
reef_client/__init__.py,sha256=sUI3vTdGLAQxZ1__KYm4ROramrVaAw00JfJsJwmBSbM,897
|
|
2
|
+
reef_client/client.py,sha256=sqzMxXIAOA5f1iZOI2Do0xvj5X8TlD8LQBRVk3kNxrk,12423
|
|
3
|
+
reef_client/serve.py,sha256=oqpXMlAxKz67HozPH1OsyNhYzn9PuxufJCwbvg1re9U,19523
|
|
4
|
+
reef_client/skill.py,sha256=O9WiSeQei7ja-k-fqgxxyV64_styvWFmmfKrKZgVLVI,1681
|
|
5
|
+
reef_client/sse.py,sha256=iTB6MrVV1AHaxC9whzzrG1nYnEqMmawCGUgJaCqpEBY,7421
|
|
6
|
+
reef_client-0.1.0.dist-info/licenses/LICENSE,sha256=T31omszuTOhhj647I0QsB-0Kt3hAD6SpVL7GqCaSV8I,11349
|
|
7
|
+
reef_client-0.1.0.dist-info/METADATA,sha256=fiDPlZrvlqxU-aYpFmeZsx77N1XJLFPyWTd5Y08UagU,2732
|
|
8
|
+
reef_client-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
9
|
+
reef_client-0.1.0.dist-info/top_level.txt,sha256=WsI2ums1v3nfD_fR47mGbtlo5Aexg1bBm8mzr37AlG4,12
|
|
10
|
+
reef_client-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor has been
|
|
163
|
+
advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Human-Agent-Society
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
reef_client
|