orsel 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.
orsel/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """orsel: the web action layer for AI agents. find, read, act, watch, explain, approve, revoke."""
2
+
3
+ from .async_client import AsyncOrsel
4
+ from .client import Orsel
5
+ from .errors import (
6
+ ApiError,
7
+ ApprovalRequiredError,
8
+ NetworkError,
9
+ OrselError,
10
+ PaymentRequiredError,
11
+ RateLimitError,
12
+ TimeoutError,
13
+ WebhookSignatureError,
14
+ )
15
+ from .site import ActionError, AsyncSite, Site
16
+ from .verify import hash_entry, recipe_content_hash, verify_ledger
17
+ from .webhooks import sign_webhook, verify_webhook
18
+
19
+ __all__ = [
20
+ "ActionError",
21
+ "AsyncSite",
22
+ "ApiError",
23
+ "ApprovalRequiredError",
24
+ "AsyncOrsel",
25
+ "NetworkError",
26
+ "Orsel",
27
+ "Site",
28
+ "OrselError",
29
+ "PaymentRequiredError",
30
+ "RateLimitError",
31
+ "TimeoutError",
32
+ "WebhookSignatureError",
33
+ "hash_entry",
34
+ "recipe_content_hash",
35
+ "sign_webhook",
36
+ "verify_ledger",
37
+ "verify_webhook",
38
+ ]
39
+ __version__ = "0.1.0"
orsel/_canonical.py ADDED
@@ -0,0 +1,94 @@
1
+ """RFC 8785 JSON canonicalization (JCS) for I-JSON values, byte-identical to the TypeScript SDK and the server.
2
+
3
+ The server hashes with ECMAScript semantics, so this mirrors them: object keys sort by UTF-16 code units (not by
4
+ Python's code point order), numbers print the way ``Number.prototype.toString`` does, strings escape the way
5
+ ``JSON.stringify`` does. Anything that would hash differently elsewhere raises instead of guessing.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ from collections.abc import Mapping
13
+ from decimal import Decimal
14
+ from typing import Any
15
+
16
+ # Integers beyond this are not exactly representable as an IEEE double, so a JavaScript reader sees a rounded value.
17
+ _MAX_SAFE_INT = 2**53
18
+
19
+
20
+ def _es_number(x: float) -> str:
21
+ """``Number.prototype.toString`` for a finite double (ECMA-262 Number::toString)."""
22
+ if x != x or x in (float("inf"), float("-inf")):
23
+ raise ValueError("non-finite number is not I-JSON")
24
+ if x == 0:
25
+ return "0" # also covers -0.0
26
+ if x < 0:
27
+ return "-" + _es_number(-x)
28
+ # Shortest round-trip digits, the same ones JavaScript picks.
29
+ _, digit_tuple, exp = Decimal(repr(x)).as_tuple()
30
+ all_digits = "".join(map(str, digit_tuple))
31
+ digits = all_digits.rstrip("0")
32
+ exp = int(exp) + len(all_digits) - len(digits)
33
+ k = len(digits)
34
+ n = k + exp # value = 0.digits * 10**n
35
+ if k <= n <= 21:
36
+ return digits + "0" * (n - k)
37
+ if 0 < n <= 21:
38
+ return digits[:n] + "." + digits[n:]
39
+ if -6 < n <= 0:
40
+ return "0." + "0" * (-n) + digits
41
+ e = n - 1
42
+ sign_char = "+" if e >= 0 else "-"
43
+ mantissa = digits if k == 1 else digits[0] + "." + digits[1:]
44
+ return f"{mantissa}e{sign_char}{abs(e)}"
45
+
46
+
47
+ def _string(s: str) -> str:
48
+ try:
49
+ s.encode("utf-8")
50
+ except UnicodeEncodeError:
51
+ raise ValueError("lone surrogate in string is not I-JSON") from None
52
+ return json.dumps(s, ensure_ascii=False)
53
+
54
+
55
+ def _utf16_key(k: str) -> bytes:
56
+ return k.encode("utf-16-be", "surrogatepass")
57
+
58
+
59
+ def _serialize(v: Any, path: str) -> str:
60
+ if v is None:
61
+ return "null"
62
+ if v is True:
63
+ return "true"
64
+ if v is False:
65
+ return "false"
66
+ if isinstance(v, str):
67
+ return _string(v)
68
+ if isinstance(v, int):
69
+ return str(v) if -_MAX_SAFE_INT <= v <= _MAX_SAFE_INT else _es_number(float(v))
70
+ if isinstance(v, float):
71
+ return _es_number(v)
72
+ if isinstance(v, (list, tuple)):
73
+ return "[" + ",".join(_serialize(x, f"{path}[{i}]") for i, x in enumerate(v)) + "]"
74
+ if isinstance(v, Mapping):
75
+ for k in v:
76
+ if not isinstance(k, str):
77
+ raise TypeError(f"{path}: object keys must be strings")
78
+ items = sorted(v.items(), key=lambda kv: _utf16_key(kv[0]))
79
+ return "{" + ",".join(f"{_string(k)}:{_serialize(x, f'{path}.{k}')}" for k, x in items) + "}"
80
+ raise TypeError(f"{path}: {type(v).__name__} is not JSON")
81
+
82
+
83
+ def canonical_json(value: Any) -> str:
84
+ """The RFC 8785 canonical form of ``value`` as text. Raises ``TypeError`` or ``ValueError`` for non-I-JSON input."""
85
+ return _serialize(value, "$")
86
+
87
+
88
+ def sha256_hex(text: str) -> str:
89
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
90
+
91
+
92
+ def digest_of(value: Any) -> str:
93
+ """SHA-256 of the canonical form of any JSON value. An approval's ``payloadHash`` is ``digest_of(payload)``."""
94
+ return sha256_hex(canonical_json(value))
orsel/_core.py ADDED
@@ -0,0 +1,201 @@
1
+ """Shared by the sync and async clients: configuration, request building, error mapping, SSE and wait helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import random
7
+ import uuid
8
+ from collections.abc import Iterable, Mapping
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Callable, Generic, TypeVar
11
+
12
+ import httpx
13
+
14
+ from .errors import ApiError, NetworkError, OrselError, PaymentRequiredError, RateLimitError
15
+
16
+ SDK_VERSION = "0.1.0"
17
+
18
+ #: The environment variable names the SDK, CLI and MCP server all read.
19
+ ENV_KEY = "ORSEL_KEY"
20
+ ENV_URL = "ORSEL_URL"
21
+ ENV_PROJECT = "ORSEL_PROJECT"
22
+
23
+ RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
24
+ #: A server cannot park the SDK for longer than this with ``Retry-After``; the error still reports the real value.
25
+ MAX_RETRY_AFTER_SECONDS = 60.0
26
+
27
+ NO_ADDRESS = (
28
+ "no address. Pass base_url=... or set ORSEL_URL to the address you open the orsel dashboard at "
29
+ "(for example http://localhost:3000)."
30
+ )
31
+ NO_KEY = (
32
+ "no api key. Pass api_key=... or set ORSEL_KEY "
33
+ "(keys look like orsel_<id>.<secret>; create one in the dashboard, under api keys)."
34
+ )
35
+
36
+ T = TypeVar("T")
37
+
38
+
39
+ def env_default(name: str) -> str | None:
40
+ """An environment variable, or None when unset or blank."""
41
+ v = os.environ.get(name, "").strip()
42
+ return v or None
43
+
44
+
45
+ def backoff_seconds(attempt: int, rand: float, base: float = 0.25, cap: float = 8.0) -> float:
46
+ """Exponential backoff with full jitter: uniform in [0, min(cap, base * 2**attempt)]."""
47
+ return float(rand * min(cap, base * (2**attempt)))
48
+
49
+
50
+ def new_idempotency_key() -> str:
51
+ return f"sdk-{uuid.uuid4()}"
52
+
53
+
54
+ def jitter() -> float:
55
+ return random.random()
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Op(Generic[T]):
60
+ """One request: what to send, whether it may be repeated, and how to read the answer."""
61
+
62
+ method: str
63
+ path: str
64
+ parse: Callable[[Any], T]
65
+ query: Mapping[str, Any] | None = None
66
+ body: Any = None
67
+ #: Retry on 408, 425, 429, 5xx and network errors. Only for requests that are safe to repeat.
68
+ retry: bool = False
69
+ headers: Mapping[str, str] = field(default_factory=dict)
70
+ #: Send no Authorization header (public routes).
71
+ anonymous: bool = False
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Prepared:
76
+ method: str
77
+ url: str
78
+ headers: dict[str, str]
79
+ json: Any | None
80
+
81
+
82
+ class Config:
83
+ def __init__(
84
+ self,
85
+ api_key: str | None,
86
+ base_url: str,
87
+ project: str | None,
88
+ retries: int,
89
+ timeout: float,
90
+ ) -> None:
91
+ if not base_url:
92
+ raise OrselError(NO_ADDRESS)
93
+ self.api_key = api_key
94
+ self.base_url = base_url.rstrip("/")
95
+ self.project = project
96
+ self.retries = max(0, retries)
97
+ self.timeout = timeout
98
+
99
+ def prepare(self, op: Op[Any], *, accept: str = "application/json") -> Prepared:
100
+ url = f"{self.base_url}{op.path}"
101
+ q = {k: _query_value(v) for k, v in (op.query or {}).items() if v is not None}
102
+ if q:
103
+ url += "?" + str(httpx.QueryParams(q))
104
+ headers = {"accept": accept, "x-sdk": f"orsel-sdk-py/{SDK_VERSION}"}
105
+ if self.api_key and not op.anonymous:
106
+ headers["authorization"] = f"Bearer {self.api_key}"
107
+ if self.project:
108
+ headers["x-project-id"] = self.project
109
+ if op.body is not None:
110
+ headers["content-type"] = "application/json"
111
+ headers.update(op.headers)
112
+ return Prepared(op.method, url, headers, op.body)
113
+
114
+
115
+ def _query_value(v: Any) -> str:
116
+ if v is True:
117
+ return "true"
118
+ if v is False:
119
+ return "false"
120
+ return str(v)
121
+
122
+
123
+ def api_error(res: httpx.Response) -> ApiError:
124
+ code, message = "unknown", f"request failed ({res.status_code})"
125
+ request_id = res.headers.get("x-request-id")
126
+ details: dict[str, Any] | None = None
127
+ try:
128
+ err = res.json().get("error")
129
+ if isinstance(err, dict):
130
+ code = str(err.get("code", code))
131
+ message = str(err.get("message", message))
132
+ request_id = err.get("requestId", request_id)
133
+ d = err.get("details")
134
+ details = d if isinstance(d, dict) else None
135
+ except Exception: # non-JSON error body
136
+ pass
137
+ if res.status_code == 429:
138
+ try:
139
+ ra = float(res.headers.get("retry-after", ""))
140
+ except ValueError:
141
+ ra = 0.0
142
+ return RateLimitError(message, request_id=request_id, retry_after=ra if ra > 0 else None, details=details)
143
+ if res.status_code == 402:
144
+ return PaymentRequiredError(message, request_id=request_id, details=details)
145
+ return ApiError(message, code=code, status=res.status_code, request_id=request_id, details=details)
146
+
147
+
148
+ def retry_wait(err: ApiError | None, attempt: int, rand: float) -> float:
149
+ if isinstance(err, RateLimitError) and err.retry_after is not None:
150
+ return min(err.retry_after, MAX_RETRY_AFTER_SECONDS)
151
+ return backoff_seconds(attempt, rand)
152
+
153
+
154
+ def network_error(base_url: str, cause: Exception) -> NetworkError:
155
+ why = str(cause) or "no response"
156
+ return NetworkError(f"could not reach {base_url} ({why}). check ORSEL_URL, your network, and that the server is up.")
157
+
158
+
159
+ def parse_sse(lines: Iterable[str]) -> Iterable[tuple[str, str]]:
160
+ """Yields (event, data) for each server-sent event in a stream of text lines."""
161
+ event: str = "message"
162
+ data: list[str] = []
163
+ for line in lines:
164
+ if line == "":
165
+ if data:
166
+ yield event, "\n".join(data)
167
+ event, data = "message", []
168
+ elif line.startswith(":"):
169
+ continue
170
+ elif line.startswith("event:"):
171
+ event = line[6:].strip()
172
+ elif line.startswith("data:"):
173
+ data.append(line[5:].removeprefix(" "))
174
+ if data:
175
+ yield event, "\n".join(data)
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class Wait:
180
+ """How long ``act(..., wait=Wait(...))`` and the ``wait`` helpers poll. All durations are seconds."""
181
+
182
+ #: Give up after this long waiting for the run. Default 30.
183
+ timeout: float = 30.0
184
+ #: How long to wait for a person to decide an approval. Default 900 (15 minutes).
185
+ approval_timeout: float = 900.0
186
+ #: First poll delay, doubled up to ``max_interval``.
187
+ interval: float = 0.1
188
+ max_interval: float = 1.0
189
+
190
+
191
+ def walk_pages(fetch: Callable[[str | None], Any]) -> Iterable[Any]:
192
+ """Yields every item of a cursor-paged list. Stops if the server repeats a cursor instead of looping forever."""
193
+ cursor: str | None = None
194
+ seen: set[str] = set()
195
+ while True:
196
+ page = fetch(cursor)
197
+ yield from page.items
198
+ cursor = page.next_cursor
199
+ if cursor is None or cursor in seen:
200
+ return
201
+ seen.add(cursor)