agentboxd 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.
agentboxd/_signup.py ADDED
@@ -0,0 +1,69 @@
1
+ """Agent self-signup: the proof-of-work solver (no I/O).
2
+
3
+ The API's challenge asks for a decimal ``solution`` such that
4
+ ``SHA-256(challenge + ":" + solution)`` starts with ``difficulty`` zero bits.
5
+ """
6
+
7
+ import hashlib
8
+ from dataclasses import dataclass
9
+ from typing import Generic, Optional, TypeVar
10
+
11
+ from ._types import Identity, Inbox, SignupResult, SignupWorkspace
12
+
13
+ __all__ = ["Signup", "leading_zero_bits", "solve_signup_challenge"]
14
+
15
+ _C = TypeVar("_C")
16
+
17
+
18
+ def leading_zero_bits(digest: bytes) -> int:
19
+ """Number of leading zero bits of a digest."""
20
+ bits = 0
21
+ for byte in digest:
22
+ if byte == 0:
23
+ bits += 8
24
+ continue
25
+ return bits + 8 - byte.bit_length()
26
+ return bits
27
+
28
+
29
+ def solve_signup_challenge(challenge: str, difficulty: int, max_iterations: int = 2**32) -> str:
30
+ """The first decimal solution (counting up from 0): about ``2**difficulty`` hashes.
31
+
32
+ At the default difficulty that is a few seconds of CPU.
33
+ """
34
+ prefix = hashlib.sha256(f"{challenge}:".encode())
35
+ for i in range(max_iterations):
36
+ h = prefix.copy()
37
+ h.update(str(i).encode())
38
+ if leading_zero_bits(h.digest()) >= difficulty:
39
+ return str(i)
40
+ raise RuntimeError(f"no solution found in {max_iterations} tries")
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Signup(Generic[_C]):
45
+ """What :meth:`Agentboxd.signup` returns: a ready client and the API's answer.
46
+
47
+ ``api_key`` is shown only once: store it (e.g. as ``AGENTBOXD_API_KEY``).
48
+ """
49
+
50
+ client: _C
51
+ result: SignupResult
52
+
53
+ @property
54
+ def api_key(self) -> str:
55
+ return self.result["api_key"]
56
+
57
+ @property
58
+ def inbox(self) -> Inbox:
59
+ """The inbox (``None`` for a ``kind="identity"`` signup: use :attr:`identity`)."""
60
+ return self.result["inbox"]
61
+
62
+ @property
63
+ def identity(self) -> Optional[Identity]:
64
+ """The identity-only agent of a ``kind="identity"`` signup, else ``None``."""
65
+ return self.result.get("identity")
66
+
67
+ @property
68
+ def workspace(self) -> SignupWorkspace:
69
+ return self.result["workspace"]
agentboxd/_stream.py ADDED
@@ -0,0 +1,151 @@
1
+ """Realtime event stream (``GET /v1/stream``) for :class:`AsyncAgentboxd`.
2
+
3
+ The same event bodies as webhooks, pushed over a WebSocket, with automatic reconnect and resume
4
+ (``since`` = the last event id seen). Needs the optional ``websockets`` package::
5
+
6
+ pip install 'agentboxd[stream]'
7
+
8
+ async with AsyncAgentboxd() as mr:
9
+ async for event in mr.stream(event_types=["message.received"]):
10
+ print(event["type"], event["data"]["message"]["subject"])
11
+ """
12
+
13
+ import asyncio
14
+ import json
15
+ import random
16
+ from collections.abc import AsyncIterator, Awaitable, Sequence
17
+ from types import TracebackType
18
+ from typing import Any, Callable, Literal, Optional
19
+
20
+ from ._errors import AgentboxdError, APIConnectionError, InternalServerError, RateLimitError
21
+ from ._types import StreamEvent
22
+
23
+ __all__ = ["EventStream", "StreamClosedError"]
24
+
25
+ _FATAL_CODES = {4001, 4003, 1009}
26
+ _MAX_BACKOFF = 30.0
27
+
28
+
29
+ class StreamClosedError(AgentboxdError):
30
+ """The server ended the stream for good: ``4001`` (credential invalid or revoked), ``4003``
31
+ (missing ``messages:read``), ``1009`` (frame too large), or a subscription the server refused."""
32
+
33
+ def __init__(self, close_code: int, reason: str, code: str = "stream_closed") -> None:
34
+ super().__init__(0, code, f"stream closed ({close_code}): {reason}")
35
+ self.close_code = close_code
36
+ self.reason = reason
37
+
38
+
39
+ def _close_code(exc: BaseException) -> tuple[int, str]:
40
+ """(code, reason) of a websockets ConnectionClosed, across websockets versions."""
41
+ rcvd = getattr(exc, "rcvd", None)
42
+ if rcvd is not None:
43
+ return int(rcvd.code), str(rcvd.reason)
44
+ return int(getattr(exc, "code", 1006) or 1006), str(getattr(exc, "reason", "") or "")
45
+
46
+
47
+ class EventStream:
48
+ """Async iterator over stream events. Reconnects and resumes unless ``reconnect=False``, also after a
49
+ failed token request (network error, 429, 5xx); a refused key or permission (401, 403) raises.
50
+
51
+ ``last_event_id`` is the id of the last event yielded; ``replay_truncated`` is ``True`` after a
52
+ (re)subscribe whose replay may have missed events (resynchronise with the REST API then).
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ mint_url: Callable[[], Awaitable[str]],
58
+ *,
59
+ inbox_ids: Optional[Sequence[str]] = None,
60
+ event_types: Optional[Sequence[str]] = None,
61
+ payload: Optional[Literal["full", "envelope"]] = None,
62
+ since: Optional[str] = None,
63
+ reconnect: bool = True,
64
+ ) -> None:
65
+ self._mint_url = mint_url
66
+ self._subscribe: dict[str, Any] = {"type": "subscribe"}
67
+ if inbox_ids:
68
+ self._subscribe["inbox_ids"] = list(inbox_ids)
69
+ if event_types:
70
+ self._subscribe["event_types"] = list(event_types)
71
+ if payload:
72
+ self._subscribe["payload"] = payload
73
+ self._reconnect = reconnect
74
+ self._closed = False
75
+ self._ws: Any = None
76
+ self.last_event_id: Optional[str] = since
77
+ self.replay_truncated = False
78
+
79
+ def __aiter__(self) -> AsyncIterator[StreamEvent]:
80
+ return self._events()
81
+
82
+ async def close(self) -> None:
83
+ """Stop the stream; the iterator ends after the current event."""
84
+ self._closed = True
85
+ if self._ws is not None:
86
+ await self._ws.close()
87
+
88
+ async def __aenter__(self) -> "EventStream":
89
+ return self
90
+
91
+ async def __aexit__(
92
+ self,
93
+ exc_type: Optional[type[BaseException]],
94
+ exc: Optional[BaseException],
95
+ tb: Optional[TracebackType],
96
+ ) -> None:
97
+ await self.close()
98
+
99
+ async def _events(self) -> AsyncIterator[StreamEvent]:
100
+ try:
101
+ import websockets
102
+ except ImportError as exc: # pragma: no cover - depends on the environment
103
+ raise ImportError(
104
+ "AsyncAgentboxd.stream() needs the websockets package: pip install 'agentboxd[stream]'"
105
+ ) from exc
106
+
107
+ attempt = 0
108
+ while not self._closed:
109
+ retry_after = 0.0
110
+ try:
111
+ # Token errors (bad key, missing permission) propagate: retrying won't help.
112
+ url = await self._mint_url()
113
+ async with websockets.connect(url, max_size=None) as ws:
114
+ self._ws = ws
115
+ async for raw in ws:
116
+ msg = json.loads(raw)
117
+ kind = msg.get("type")
118
+ if kind == "hello":
119
+ sub = dict(self._subscribe)
120
+ if self.last_event_id:
121
+ sub["since"] = self.last_event_id
122
+ await ws.send(json.dumps(sub))
123
+ elif kind == "subscribed":
124
+ attempt = 0
125
+ self.replay_truncated = bool(msg.get("replay_truncated"))
126
+ elif kind == "event":
127
+ event: StreamEvent = msg["event"]
128
+ self.last_event_id = event["id"]
129
+ yield event
130
+ elif kind == "error":
131
+ # Every error the server sends is about our own subscription.
132
+ raise StreamClosedError(1008, str(msg.get("message")), str(msg.get("code")))
133
+ except (APIConnectionError, InternalServerError, RateLimitError) as exc:
134
+ # The token request failed (network down, API restarting, rate limited): retry below.
135
+ if not self._reconnect:
136
+ raise
137
+ retry_after = exc.retry_after or 0.0
138
+ except websockets.ConnectionClosed as exc:
139
+ code, reason = _close_code(exc)
140
+ if code in _FATAL_CODES:
141
+ raise StreamClosedError(code, reason) from exc
142
+ except (OSError, asyncio.TimeoutError, websockets.InvalidHandshake):
143
+ pass # network trouble: retry below
144
+ finally:
145
+ self._ws = None
146
+ if self._closed or not self._reconnect:
147
+ return
148
+ base = min(_MAX_BACKOFF, 2.0**attempt)
149
+ if base < _MAX_BACKOFF:
150
+ attempt += 1 # stop at the cap: a long outage would overflow 2.0**attempt
151
+ await asyncio.sleep(max(retry_after, base / 2 + random.random() * base / 2))