spredr 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.
spredr/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """spredr: build an AI agent as an ordinary service and run it on spredr.
2
+
3
+ Agent inside the agent: take tasks, ask before risky actions, remember, report each step
4
+ Caller in your backend: give the agent tasks, follow them, answer its questions
5
+ Spredr you, with your token: register agents, link backends, schedule work, set limits
6
+ """
7
+
8
+ from ._json import Record
9
+ from ._sign import ai_verifier, new_keys
10
+ from ._tag import current_task
11
+ from .agent import Agent, Answer
12
+ from .caller import Caller
13
+ from .context import Context, Memory
14
+ from .errors import (
15
+ AuthenticationError,
16
+ BadRequestError,
17
+ ConflictError,
18
+ ConnectionError,
19
+ InternalServerError,
20
+ NotFoundError,
21
+ PartError,
22
+ PermissionDeniedError,
23
+ RateLimitError,
24
+ SpredrError,
25
+ TaskError,
26
+ TimeoutError,
27
+ )
28
+ from .owner import DEFAULT_AI_URL, OwnedAgent, Spredr
29
+ from .tasks import Tasks, Tenant
30
+
31
+ __version__ = "0.1.0"
32
+ __all__ = [
33
+ "Agent", "Answer", "AuthenticationError", "BadRequestError", "Caller", "ConflictError", "ConnectionError", "Context", "DEFAULT_AI_URL",
34
+ "InternalServerError", "Memory", "NotFoundError", "OwnedAgent", "PartError", "PermissionDeniedError", "RateLimitError", "Record",
35
+ "Spredr", "SpredrError", "TaskError", "Tasks", "Tenant", "TimeoutError", "ai_verifier", "current_task", "new_keys",
36
+ ]
spredr/_http.py ADDED
@@ -0,0 +1,191 @@
1
+ """Talking to ai: signed (an agent, a caller) or with a token (you), over the standard library's HTTP in a worker
2
+ thread, so the event loop never waits on the network. What can be sent twice is retried with backoff, and a 429 or 503
3
+ that says when to come back (Retry-After) is retried then, whatever the method."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import email.utils
9
+ import random
10
+ import threading
11
+ import time
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ from typing import Any, AsyncIterator, Mapping
16
+
17
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
18
+
19
+ from . import errors
20
+ from ._json import Record, dumps, loads
21
+ from ._sign import signed_headers
22
+
23
+ TIMEOUT_S = 75.0
24
+ STREAM_TIMEOUT_S = 11 * 60.0
25
+ MAX_RETRIES = 2
26
+ RETRY_DELAY_S = 0.5
27
+ _MAX_DELAY_S = 8.0
28
+ _MAX_RETRY_AFTER_S = 60.0
29
+ _REPEATABLE = {"GET", "PUT", "DELETE"}
30
+ _END = object()
31
+
32
+
33
+ def query(**values: Any) -> str:
34
+ pairs = [f"{key}={urllib.parse.quote(str(value), safe='')}" for key, value in values.items() if value is not None]
35
+ return f"?{'&'.join(pairs)}" if pairs else ""
36
+
37
+
38
+ def _retry_after(headers: Mapping[str, str]) -> float | None:
39
+ header = headers.get("retry-after") or headers.get("Retry-After")
40
+ if not header:
41
+ return None
42
+ try:
43
+ return max(0.0, float(header))
44
+ except ValueError:
45
+ try:
46
+ return max(0.0, email.utils.parsedate_to_datetime(header).timestamp() - time.time())
47
+ except (TypeError, ValueError):
48
+ return None
49
+
50
+
51
+ def _failure(status: int, headers: Mapping[str, str], raw: bytes) -> errors.SpredrError:
52
+ text = raw.decode("utf-8", "replace")
53
+ try:
54
+ parsed = loads(text)
55
+ except ValueError:
56
+ parsed = None
57
+ field = (lambda name: parsed.get(name) if isinstance(parsed, dict) and isinstance(parsed.get(name), str) else "")
58
+ message = field("error") or text[:300].strip() or f"HTTP {status}"
59
+ return errors.error_for(status, message, field("trace"), _retry_after(headers))
60
+
61
+
62
+ class Client:
63
+ def __init__(self, base: str, *, token: str | None = None, sender: str | None = None, key: Ed25519PrivateKey | None = None,
64
+ timeout: float = TIMEOUT_S, max_retries: int = MAX_RETRIES, retry_delay: float = RETRY_DELAY_S) -> None:
65
+ self._root = base.rstrip("/")
66
+ self._token = token
67
+ self._sender = sender
68
+ self._key = key
69
+ self._timeout = timeout
70
+ self._max_retries = max(0, max_retries)
71
+ self._delay = retry_delay
72
+
73
+ def _headers(self, method: str, path: str, body: bytes, accept: str) -> dict[str, str]:
74
+ headers = {"accept": accept}
75
+ if body and accept == "application/json":
76
+ headers["content-type"] = "application/json"
77
+ if self._token:
78
+ headers["authorization"] = f"Bearer {self._token}"
79
+ elif self._sender and self._key:
80
+ headers.update(signed_headers(self._sender, self._key, method, path, body))
81
+ return headers
82
+
83
+ def _wait(self, attempt: int, retry_after: float | None) -> None:
84
+ backoff = min(_MAX_DELAY_S, self._delay * 2**attempt) * (0.75 + random.random() * 0.5)
85
+ time.sleep(backoff if retry_after is None else retry_after)
86
+
87
+ def _send(self, method: str, path: str, body: bytes, accept: str, repeatable: bool, extra: Mapping[str, str] | None = None,
88
+ timeout: float | None = None, stream: bool = False) -> tuple[int, dict[str, str], Any]:
89
+ """(status, headers, body bytes) — or the open response when stream. Retries what may be retried."""
90
+ attempt = 0
91
+ while True:
92
+ last = attempt >= self._max_retries
93
+ headers = {**self._headers(method, path, body, accept), **(extra or {})}
94
+ request = urllib.request.Request(f"{self._root}{path}", data=body or None, method=method, headers=headers)
95
+ try:
96
+ response = urllib.request.urlopen(request, timeout=timeout or self._timeout) # noqa: S310 (ai's own address)
97
+ if stream:
98
+ return response.status, dict(response.headers), response
99
+ with response:
100
+ return response.status, dict(response.headers), response.read()
101
+ except urllib.error.HTTPError as answer:
102
+ with answer:
103
+ status, answer_headers, raw = answer.code, dict(answer.headers), answer.read()
104
+ if last:
105
+ return status, answer_headers, raw
106
+ retry_after = _retry_after(answer_headers)
107
+ turned_away = status in (429, 503) and retry_after is not None and retry_after <= _MAX_RETRY_AFTER_S
108
+ if not (turned_away or (status != 429 and repeatable and (status == 408 or status >= 500))):
109
+ return status, answer_headers, raw
110
+ self._wait(attempt, retry_after)
111
+ except (urllib.error.URLError, OSError) as failure:
112
+ if not repeatable or last:
113
+ timed_out = isinstance(failure, TimeoutError) or "timed out" in str(failure)
114
+ if timed_out:
115
+ raise errors.TimeoutError(0, f"ai did not answer in {self._timeout:g} s ({method} {path}).") from failure
116
+ raise errors.ConnectionError(0, f"ai could not be reached ({method} {path}): {failure}") from failure
117
+ self._wait(attempt, None)
118
+ attempt += 1
119
+
120
+ def _json(self, method: str, path: str, status: int, headers: Mapping[str, str], raw: bytes) -> Any:
121
+ if status >= 400:
122
+ raise _failure(status, headers, raw)
123
+ try:
124
+ return loads(raw.decode("utf-8"))
125
+ except ValueError as failure:
126
+ raise errors.SpredrError(status, f"ai answered {method} {path} with something that is not JSON.") from failure
127
+
128
+ async def call(self, method: str, path: str, body: Any = None, *, idempotent: bool | None = None) -> Any:
129
+ data = b"" if body is None else dumps(body)
130
+ repeatable = idempotent if idempotent is not None else method in _REPEATABLE
131
+ status, headers, raw = await asyncio.to_thread(self._send, method, path, data, "application/json", repeatable)
132
+ return self._json(method, path, status, headers, raw)
133
+
134
+ async def text(self, path: str) -> str:
135
+ status, headers, raw = await asyncio.to_thread(self._send, "GET", path, b"", "*/*", True)
136
+ if status >= 400:
137
+ raise _failure(status, headers, raw)
138
+ return raw.decode("utf-8")
139
+
140
+ async def upload(self, path: str, data: bytes, headers: Mapping[str, str]) -> Any:
141
+ extra = {"content-type": "application/octet-stream", **headers}
142
+ status, answer_headers, raw = await asyncio.to_thread(self._send, "PUT", path, data, "application/json", True, extra)
143
+ return self._json("PUT", path, status, answer_headers, raw)
144
+
145
+ async def download(self, path: str) -> tuple[bytes, str]:
146
+ status, headers, raw = await asyncio.to_thread(self._send, "GET", path, b"", "*/*", True)
147
+ if status >= 400:
148
+ raise _failure(status, headers, raw)
149
+ lower = {name.lower(): value for name, value in headers.items()}
150
+ return raw, lower.get("content-type", "application/octet-stream")
151
+
152
+ async def events(self, path: str, last_id: int) -> AsyncIterator[Record]:
153
+ """Server-sent events from a GET that stays open, after the event last_id; ends when the server closes it."""
154
+ loop = asyncio.get_running_loop()
155
+ queue: asyncio.Queue[Any] = asyncio.Queue()
156
+ extra = {"accept": "text/event-stream", **({"last-event-id": str(last_id)} if last_id else {})}
157
+
158
+ def pump() -> None:
159
+ try:
160
+ status, headers, response = self._send("GET", path, b"", "text/event-stream", True, extra, STREAM_TIMEOUT_S, stream=True)
161
+ if status >= 400:
162
+ raise _failure(status, headers, response if isinstance(response, bytes) else response.read())
163
+ block: list[str] = []
164
+ with response:
165
+ for raw in response:
166
+ line = raw.decode("utf-8").rstrip("\r\n")
167
+ if line:
168
+ block.append(line)
169
+ continue
170
+ fields: dict[str, list[str]] = {}
171
+ for entry in block:
172
+ name, _, value = entry.partition(":")
173
+ fields.setdefault(name, []).append(value.lstrip())
174
+ block = []
175
+ data = "\n".join(fields.get("data", []))
176
+ if data:
177
+ ident = "".join(fields.get("id", []))
178
+ sent = Record(id=int(ident) if ident.isdigit() else 0, event="".join(fields.get("event", [])) or "message", data=data)
179
+ loop.call_soon_threadsafe(queue.put_nowait, sent)
180
+ loop.call_soon_threadsafe(queue.put_nowait, _END)
181
+ except BaseException as failure: # noqa: BLE001 (handed to the loop, raised there)
182
+ loop.call_soon_threadsafe(queue.put_nowait, failure)
183
+
184
+ threading.Thread(target=pump, daemon=True).start()
185
+ while True:
186
+ item = await queue.get()
187
+ if item is _END:
188
+ return
189
+ if isinstance(item, BaseException):
190
+ raise item
191
+ yield item
spredr/_json.py ADDED
@@ -0,0 +1,60 @@
1
+ """JSON in and out: what ai answers reads as attributes (task.status, task.created_at) as well as keys, and what the
2
+ SDK sends takes the names ai knows (snake_case arguments become camelCase fields)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import dataclasses
7
+ import json
8
+ import re
9
+ from typing import Any
10
+
11
+ _SNAKE = re.compile(r"_([a-z0-9])")
12
+
13
+
14
+ def camel(name: str) -> str:
15
+ """sleep_after_minutes → sleepAfterMinutes; a name already in camelCase stays as it is."""
16
+ return _SNAKE.sub(lambda match: match.group(1).upper(), name)
17
+
18
+
19
+ def camel_keys(value: Any) -> Any:
20
+ """Every key of a dict (and of the dicts inside it) in camelCase."""
21
+ if isinstance(value, dict):
22
+ return {camel(key) if isinstance(key, str) else key: camel_keys(item) for key, item in value.items()}
23
+ if isinstance(value, (list, tuple)):
24
+ return [camel_keys(item) for item in value]
25
+ return value
26
+
27
+
28
+ class Record(dict):
29
+ """A JSON object from ai: read it as a dict, or by attribute in either spelling (task.createdAt, task.created_at)."""
30
+
31
+ __slots__ = ()
32
+
33
+ def __getattr__(self, name: str) -> Any:
34
+ if name in self:
35
+ return self[name]
36
+ spelled = camel(name)
37
+ if spelled in self:
38
+ return self[spelled]
39
+ raise AttributeError(name)
40
+
41
+
42
+ def loads(text: str | bytes) -> Any:
43
+ return json.loads(text, object_hook=Record) if text else None
44
+
45
+
46
+ def plain(value: Any) -> Any:
47
+ """What can travel as JSON: pydantic models (the Anthropic and OpenAI clients' answers) and dataclasses as dicts."""
48
+ dump = getattr(value, "model_dump", None)
49
+ if callable(dump):
50
+ try:
51
+ return dump(mode="json")
52
+ except TypeError:
53
+ return dump()
54
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
55
+ return dataclasses.asdict(value)
56
+ return value
57
+
58
+
59
+ def dumps(value: Any) -> bytes:
60
+ return json.dumps(value, separators=(",", ":"), ensure_ascii=False, default=plain).encode("utf-8")
spredr/_sign.py ADDED
@@ -0,0 +1,91 @@
1
+ """Every request between ai and its parties is signed with ed25519: method, path, time, nonce and the body's sha256,
2
+ one per line. Keys travel as base64 DER (PKCS#8 for the private one, SPKI for the public one), the same as the Node SDK."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ import hashlib
8
+ import re
9
+ import secrets
10
+ import time
11
+ from datetime import datetime, timezone
12
+ from typing import Callable, Mapping
13
+
14
+ from cryptography.exceptions import InvalidSignature
15
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
16
+ from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat, PublicFormat, load_der_private_key, load_der_public_key
17
+
18
+ HEADER_FROM = "x-spredr-from"
19
+ HEADER_TIME = "x-spredr-time"
20
+ HEADER_NONCE = "x-spredr-nonce"
21
+ HEADER_SIGNATURE = "x-spredr-signature"
22
+ AI_SIGNER = "ai"
23
+ _SKEW_S = 5 * 60
24
+ _NONCE = re.compile(r"^[0-9a-f]{32}$")
25
+
26
+
27
+ def private_key_of(text: str) -> Ed25519PrivateKey:
28
+ key = load_der_private_key(base64.b64decode(text), password=None)
29
+ if not isinstance(key, Ed25519PrivateKey):
30
+ raise ValueError("The key is not an ed25519 private key.")
31
+ return key
32
+
33
+
34
+ def public_key_of(text: str) -> Ed25519PublicKey:
35
+ key = load_der_public_key(base64.b64decode(text))
36
+ if not isinstance(key, Ed25519PublicKey):
37
+ raise ValueError("The key is not an ed25519 public key.")
38
+ return key
39
+
40
+
41
+ def new_keys() -> dict[str, str]:
42
+ """A new pair, as spredr stores them: {'private_key': …, 'public_key': …} in base64 DER."""
43
+ key = Ed25519PrivateKey.generate()
44
+ return {
45
+ "private_key": base64.b64encode(key.private_bytes(Encoding.DER, PrivateFormat.PKCS8, NoEncryption())).decode(),
46
+ "public_key": base64.b64encode(key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)).decode(),
47
+ }
48
+
49
+
50
+ def _to_sign(method: str, path: str, moment: str, nonce: str, body: bytes) -> bytes:
51
+ return "\n".join([method.upper(), path, moment, nonce, hashlib.sha256(body).hexdigest()]).encode()
52
+
53
+
54
+ def signed_headers(sender: str, key: Ed25519PrivateKey, method: str, path: str, body: bytes) -> dict[str, str]:
55
+ moment = datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
56
+ nonce = secrets.token_hex(16)
57
+ signature = base64.b64encode(key.sign(_to_sign(method, path, moment, nonce, body))).decode()
58
+ return {HEADER_FROM: sender, HEADER_TIME: moment, HEADER_NONCE: nonce, HEADER_SIGNATURE: signature}
59
+
60
+
61
+ def _seconds_of(text: str) -> float | None:
62
+ try:
63
+ return datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp()
64
+ except ValueError:
65
+ return None
66
+
67
+
68
+ def ai_verifier(ai_public_key: str) -> Callable[[str, str, Mapping[str, str], bytes], bool]:
69
+ """Checks that a request comes from ai: its signature, its time (five minutes either way) and a nonce never seen.
70
+ Give it the raw body exactly as it arrived: the signature is over those bytes."""
71
+ key = public_key_of(ai_public_key)
72
+ seen: dict[str, float] = {}
73
+
74
+ def verify(method: str, path: str, headers: Mapping[str, str], body: bytes) -> bool:
75
+ lower = {name.lower(): value for name, value in headers.items()}
76
+ moment = lower.get(HEADER_TIME, "")
77
+ nonce = lower.get(HEADER_NONCE, "")
78
+ at = _seconds_of(moment)
79
+ now = time.time()
80
+ if lower.get(HEADER_FROM) != AI_SIGNER or at is None or abs(now - at) > _SKEW_S or not _NONCE.match(nonce) or nonce in seen:
81
+ return False
82
+ try:
83
+ key.verify(base64.b64decode(lower.get(HEADER_SIGNATURE, "")), _to_sign(method, path, moment, nonce, body))
84
+ except (InvalidSignature, ValueError):
85
+ return False
86
+ for old in [old for old, until in seen.items() if until <= now]:
87
+ del seen[old]
88
+ seen[nonce] = now + 2 * _SKEW_S
89
+ return True
90
+
91
+ return verify
spredr/_tag.py ADDED
@@ -0,0 +1,41 @@
1
+ """Which task the code is working on: lines logged while a task works start with its id ([tsk_…] …), so its logs in
2
+ spredr find them. Through logging (print is left alone); a logger of its own can read current_task()."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import contextvars
7
+ import logging
8
+
9
+ _working: contextvars.ContextVar[str | None] = contextvars.ContextVar("spredr_task", default=None)
10
+ _tagged = False
11
+
12
+
13
+ def current_task() -> str | None:
14
+ """The id of the task the code is working on now, or None outside one."""
15
+ return _working.get()
16
+
17
+
18
+ def enter(task_id: str) -> contextvars.Token[str | None]:
19
+ return _working.set(task_id)
20
+
21
+
22
+ def leave(token: contextvars.Token[str | None]) -> None:
23
+ _working.reset(token)
24
+
25
+
26
+ def tag_logging() -> None:
27
+ global _tagged
28
+ if _tagged:
29
+ return
30
+ _tagged = True
31
+ make = logging.getLogRecordFactory()
32
+
33
+ def tagged(*args: object, **kwargs: object) -> logging.LogRecord:
34
+ record = make(*args, **kwargs)
35
+ task = _working.get()
36
+ record.task = task # type: ignore[attr-defined]
37
+ if task and isinstance(record.msg, str):
38
+ record.msg = f"[{task}] {record.msg}"
39
+ return record
40
+
41
+ logging.setLogRecordFactory(tagged)
spredr/_usage.py ADDED
@@ -0,0 +1,45 @@
1
+ """The model and the tokens of a model's answer, read from what the Anthropic and OpenAI clients give back (objects or
2
+ dicts), for ctx.model() to report without being told."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Any
7
+
8
+ from ._json import plain
9
+
10
+
11
+ def _number(source: dict[str, Any], *names: str) -> float | None:
12
+ for name in names:
13
+ value = source.get(name)
14
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
15
+ return value
16
+ return None
17
+
18
+
19
+ def usage_of(answer: Any) -> dict[str, Any]:
20
+ answer = plain(answer)
21
+ if not isinstance(answer, dict):
22
+ return {}
23
+ response = answer.get("response") if isinstance(answer.get("response"), dict) else {}
24
+ model = answer.get("model") if isinstance(answer.get("model"), str) else response.get("modelId") if isinstance(response.get("modelId"), str) else None
25
+ usage = answer.get("usage") if isinstance(answer.get("usage"), dict) else {}
26
+ tokens_in = _number(usage, "input_tokens", "prompt_tokens", "inputTokens", "promptTokens")
27
+ tokens_out = _number(usage, "output_tokens", "completion_tokens", "outputTokens", "completionTokens")
28
+ details = next((usage[name] for name in ("input_tokens_details", "prompt_tokens_details") if isinstance(usage.get(name), dict)), {})
29
+ cached_inside = _number(details, "cached_tokens")
30
+ if cached_inside is None:
31
+ cached_inside = _number(usage, "cachedInputTokens")
32
+ cache_read = cached_inside if cached_inside is not None else _number(usage, "cache_read_input_tokens")
33
+ cache_write = _number(usage, "cache_creation_input_tokens")
34
+ found: dict[str, Any] = {}
35
+ if model:
36
+ found["model"] = model
37
+ if tokens_in is not None:
38
+ found["tokensIn"] = max(0, tokens_in - (cached_inside or 0))
39
+ if tokens_out is not None:
40
+ found["tokensOut"] = tokens_out
41
+ if cache_read:
42
+ found["cacheReadTokens"] = cache_read
43
+ if cache_write:
44
+ found["cacheWriteTokens"] = cache_write
45
+ return found