genlava-sdk 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.
@@ -0,0 +1,20 @@
1
+ from .client import (
2
+ GenlavaApiError,
3
+ GenlavaClient,
4
+ GenlavaCompatibilityError,
5
+ GenlavaError,
6
+ GenlavaTransportError,
7
+ TransportResponse,
8
+ create_idempotency_key,
9
+ )
10
+ from .generated import * # noqa: F401,F403
11
+
12
+ __all__ = [
13
+ "GenlavaApiError",
14
+ "GenlavaClient",
15
+ "GenlavaCompatibilityError",
16
+ "GenlavaError",
17
+ "GenlavaTransportError",
18
+ "TransportResponse",
19
+ "create_idempotency_key",
20
+ ]
genlava_sdk/client.py ADDED
@@ -0,0 +1,335 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ import json
5
+ import re
6
+ from typing import Any, Callable, Mapping
7
+ from urllib.error import HTTPError, URLError
8
+ from urllib.parse import quote, urlsplit
9
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
10
+ from uuid import uuid4
11
+
12
+ from .generated import (
13
+ API_MAJOR,
14
+ CHECK_REQUEST_SCHEMA_VERSION,
15
+ CHECK_RESPONSE_SCHEMA_VERSION,
16
+ COMPLETION_REQUEST_SCHEMA_VERSION,
17
+ COMPLETION_RESPONSE_SCHEMA_VERSION,
18
+ IDEMPOTENCY_KEY_PATTERN,
19
+ OPERATIONS,
20
+ PREPARE_REQUEST_SCHEMA_VERSION,
21
+ PREPARE_RESPONSE_SCHEMA_VERSION,
22
+ )
23
+
24
+ _IDEMPOTENCY_RE = re.compile(IDEMPOTENCY_KEY_PATTERN)
25
+ _PREFIX_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._~-]{1,31}$")
26
+ MAX_SDK_RESPONSE_BYTES = 512 * 1024
27
+
28
+
29
+ class _NoApiRedirect(HTTPRedirectHandler):
30
+ # urllib's default redirect behavior must not forward a bearer API key
31
+ # to an attacker-controlled Location. No redirect is necessary for v1.
32
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
33
+ return None
34
+
35
+
36
+ _NO_REDIRECT_OPENER = build_opener(_NoApiRedirect)
37
+
38
+
39
+ def _bounded_body(stream) -> bytes:
40
+ body = stream.read(MAX_SDK_RESPONSE_BYTES + 1)
41
+ if len(body) > MAX_SDK_RESPONSE_BYTES:
42
+ raise GenlavaTransportError("Genlava API response exceeded the SDK size limit.", retryable=False)
43
+ return body
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class TransportResponse:
48
+ status: int
49
+ headers: Mapping[str, str]
50
+ body: bytes
51
+
52
+
53
+ class GenlavaError(Exception):
54
+ pass
55
+
56
+
57
+ class GenlavaTransportError(GenlavaError):
58
+ def __init__(self, message: str, *, retryable: bool = True) -> None:
59
+ super().__init__(message)
60
+ self.retryable = retryable
61
+
62
+
63
+ class GenlavaCompatibilityError(GenlavaError):
64
+ def __init__(self, received_version: str | None) -> None:
65
+ super().__init__("Genlava API version is incompatible with this SDK.")
66
+ self.expected_version = API_MAJOR
67
+ self.received_version = received_version
68
+
69
+
70
+ class GenlavaApiError(GenlavaError):
71
+ def __init__(self, status: int, payload: Mapping[str, Any], headers: Mapping[str, str]) -> None:
72
+ error = payload.get("error") if isinstance(payload, Mapping) else None
73
+ error = error if isinstance(error, Mapping) else {}
74
+ super().__init__(
75
+ error.get("message") if isinstance(error.get("message"), str) else "Genlava API request failed."
76
+ )
77
+ self.status = status
78
+ self.code = error.get("code") if isinstance(error.get("code"), str) else "unknown_api_error"
79
+ self.request_id = error.get("requestId") if isinstance(error.get("requestId"), str) else None
80
+ self.retryable = error.get("retryable") is True
81
+ self.authentication_required = error.get("authenticationRequired") is True
82
+ self.authorization_required = error.get("authorizationRequired") is True
83
+ self.supported_version = (
84
+ error.get("supportedVersion") if isinstance(error.get("supportedVersion"), str) else None
85
+ )
86
+ self.details = dict(error["details"]) if isinstance(error.get("details"), Mapping) else None
87
+ self.retry_after_seconds = _nonnegative_int(headers.get("retry-after"))
88
+
89
+
90
+ Transport = Callable[[str, str, Mapping[str, str], bytes, float], TransportResponse]
91
+
92
+
93
+ def _nonnegative_int(value: Any) -> int | None:
94
+ try:
95
+ parsed = int(value)
96
+ except (TypeError, ValueError):
97
+ return None
98
+ return parsed if parsed >= 0 else None
99
+
100
+
101
+ def _normalize_headers(headers: Mapping[str, str]) -> dict[str, str]:
102
+ return {str(key).lower(): str(value) for key, value in headers.items()}
103
+
104
+
105
+ def _default_transport(
106
+ method: str,
107
+ url: str,
108
+ headers: Mapping[str, str],
109
+ body: bytes,
110
+ timeout: float,
111
+ ) -> TransportResponse:
112
+ request = Request(url, method=method, headers=dict(headers), data=body)
113
+ try:
114
+ with _NO_REDIRECT_OPENER.open(request, timeout=timeout) as response:
115
+ return TransportResponse(response.status, _normalize_headers(response.headers), _bounded_body(response))
116
+ except HTTPError as error:
117
+ return TransportResponse(error.code, _normalize_headers(error.headers), _bounded_body(error))
118
+ except (URLError, TimeoutError, OSError) as error:
119
+ raise GenlavaTransportError("Genlava API transport failed.") from error
120
+
121
+
122
+ def _base_url(value: str) -> str:
123
+ if not isinstance(value, str) or not value:
124
+ raise TypeError("base_url is required")
125
+ parsed = urlsplit(value)
126
+ if parsed.scheme != "https":
127
+ raise TypeError("base_url must use https")
128
+ if not parsed.netloc or parsed.username or parsed.password or parsed.query or parsed.fragment:
129
+ raise TypeError("base_url must be a credential-free HTTPS origin")
130
+ if parsed.path not in ("", "/"):
131
+ raise TypeError("base_url must be an origin without a path")
132
+ return f"https://{parsed.netloc}"
133
+
134
+
135
+ def _api_key(value: str) -> str:
136
+ if not isinstance(value, str) or len(value) < 16 or len(value) > 1024 or any(char.isspace() for char in value):
137
+ raise TypeError("api_key is invalid")
138
+ return value
139
+
140
+
141
+ def _idempotency_key(value: str) -> str:
142
+ if not isinstance(value, str) or _IDEMPOTENCY_RE.fullmatch(value) is None:
143
+ raise TypeError("idempotency_key is invalid")
144
+ return value
145
+
146
+
147
+ def _interaction_id(value: str) -> str:
148
+ if not isinstance(value, str) or not 8 <= len(value) <= 160:
149
+ raise TypeError("interaction_id is invalid")
150
+ return value
151
+
152
+
153
+ def create_idempotency_key(prefix: str = "sdk") -> str:
154
+ if not isinstance(prefix, str) or _PREFIX_RE.fullmatch(prefix) is None:
155
+ raise TypeError("idempotency key prefix is invalid")
156
+ return _idempotency_key(f"{prefix}:{uuid4()}")
157
+
158
+
159
+ class GenlavaClient:
160
+ def __init__(
161
+ self,
162
+ *,
163
+ base_url: str,
164
+ api_key: str,
165
+ transport: Transport | None = None,
166
+ timeout_seconds: float = 10.0,
167
+ ) -> None:
168
+ if not isinstance(timeout_seconds, (int, float)) or not 0.1 <= float(timeout_seconds) <= 120.0:
169
+ raise TypeError("timeout_seconds must be between 0.1 and 120")
170
+ self._base_url = _base_url(base_url)
171
+ self._api_key = _api_key(api_key)
172
+ self._transport = transport or _default_transport
173
+ self._timeout = float(timeout_seconds)
174
+
175
+ def _request(
176
+ self,
177
+ operation: Mapping[str, str],
178
+ payload: Mapping[str, Any],
179
+ *,
180
+ expected_schema_version: str,
181
+ idempotency_key: str | None = None,
182
+ ) -> dict[str, Any]:
183
+ headers: dict[str, str] = {
184
+ "accept": "application/json",
185
+ "authorization": f"Bearer {self._api_key}",
186
+ "content-type": "application/json",
187
+ }
188
+ if idempotency_key is not None:
189
+ headers["idempotency-key"] = _idempotency_key(idempotency_key)
190
+
191
+ body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
192
+ response = self._transport(
193
+ operation["method"],
194
+ f"{self._base_url}{operation['path']}",
195
+ headers,
196
+ body,
197
+ self._timeout,
198
+ )
199
+ if not isinstance(response.body, bytes) or len(response.body) > MAX_SDK_RESPONSE_BYTES:
200
+ raise GenlavaTransportError("Genlava API response exceeded the SDK size limit.", retryable=False)
201
+ normalized_headers = _normalize_headers(response.headers)
202
+ declared = normalized_headers.get("content-length")
203
+ if declared is not None and (not declared.isascii() or not declared.isdigit()
204
+ or int(declared) > MAX_SDK_RESPONSE_BYTES):
205
+ raise GenlavaTransportError("Genlava API response exceeded the SDK size limit.", retryable=False)
206
+ content_type = normalized_headers.get("content-type", "")
207
+ if not content_type.lower().startswith("application/json"):
208
+ raise GenlavaTransportError("Genlava API returned a non-JSON response.")
209
+
210
+ try:
211
+ parsed = json.loads(response.body.decode("utf-8"))
212
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
213
+ raise GenlavaTransportError("Genlava API returned invalid JSON.") from error
214
+
215
+ if not isinstance(parsed, Mapping):
216
+ raise GenlavaTransportError("Genlava API returned a non-object JSON response.")
217
+ if response.status < 200 or response.status >= 300:
218
+ raise GenlavaApiError(response.status, parsed, normalized_headers)
219
+
220
+ received_version = normalized_headers.get("x-genlava-api-version")
221
+ if received_version != API_MAJOR:
222
+ raise GenlavaCompatibilityError(received_version)
223
+ if parsed.get("schemaVersion") != expected_schema_version:
224
+ raise GenlavaCompatibilityError(received_version)
225
+
226
+ return {
227
+ "data": dict(parsed),
228
+ "request_id": normalized_headers.get("x-request-id"),
229
+ "usage": {
230
+ "limit": _nonnegative_int(normalized_headers.get("ratelimit-limit")),
231
+ "remaining": _nonnegative_int(normalized_headers.get("ratelimit-remaining")),
232
+ "reset": _nonnegative_int(normalized_headers.get("ratelimit-reset")),
233
+ },
234
+ }
235
+
236
+ def check(self, input: Mapping[str, Any]) -> dict[str, Any]:
237
+ if not isinstance(input, Mapping):
238
+ raise TypeError("check input must be a mapping")
239
+ return self._request(
240
+ OPERATIONS["checkCounterparty"],
241
+ {
242
+ "schemaVersion": CHECK_REQUEST_SCHEMA_VERSION,
243
+ "identifier": input.get("identifier"),
244
+ "action": input.get("action"),
245
+ "effectiveAt": input.get("effectiveAt"),
246
+ "taskCode": input.get("taskCode"),
247
+ "contextRef": input.get("contextRef"),
248
+ },
249
+ expected_schema_version=CHECK_RESPONSE_SCHEMA_VERSION,
250
+ )
251
+
252
+ def prepare_interaction(
253
+ self,
254
+ input: Mapping[str, Any],
255
+ *,
256
+ idempotency_key: str,
257
+ ) -> dict[str, Any]:
258
+ if not isinstance(input, Mapping):
259
+ raise TypeError("prepare input must be a mapping")
260
+ return self._request(
261
+ OPERATIONS["prepareInteraction"],
262
+ {
263
+ "schemaVersion": PREPARE_REQUEST_SCHEMA_VERSION,
264
+ "counterpartyId": input.get("counterpartyId"),
265
+ "action": input.get("action"),
266
+ "targetRef": input.get("targetRef"),
267
+ "memoryCommitmentRef": input.get("memoryCommitmentRef"),
268
+ },
269
+ expected_schema_version=PREPARE_RESPONSE_SCHEMA_VERSION,
270
+ idempotency_key=_idempotency_key(idempotency_key),
271
+ )
272
+
273
+ def complete_interaction(
274
+ self,
275
+ interaction_id: str,
276
+ input: Mapping[str, Any],
277
+ *,
278
+ idempotency_key: str,
279
+ ) -> dict[str, Any]:
280
+ if not isinstance(input, Mapping):
281
+ raise TypeError("completion input must be a mapping")
282
+ operation = dict(OPERATIONS["completeInteraction"])
283
+ operation["path"] = operation["path"].replace(
284
+ "{interactionId}", quote(_interaction_id(interaction_id), safe="")
285
+ )
286
+ return self._request(
287
+ operation,
288
+ {
289
+ "schemaVersion": COMPLETION_REQUEST_SCHEMA_VERSION,
290
+ "kind": input.get("kind"),
291
+ "outcomeClass": input.get("outcomeClass"),
292
+ "reasonCategory": input.get("reasonCategory"),
293
+ "expectedRevision": input.get("expectedRevision"),
294
+ },
295
+ expected_schema_version=COMPLETION_RESPONSE_SCHEMA_VERSION,
296
+ idempotency_key=_idempotency_key(idempotency_key),
297
+ )
298
+
299
+ def record_outcome(
300
+ self,
301
+ *,
302
+ interaction_id: str,
303
+ outcome_class: str,
304
+ expected_revision: int,
305
+ idempotency_key: str,
306
+ ) -> dict[str, Any]:
307
+ return self.complete_interaction(
308
+ interaction_id,
309
+ {
310
+ "kind": "outcome",
311
+ "outcomeClass": outcome_class,
312
+ "reasonCategory": None,
313
+ "expectedRevision": expected_revision,
314
+ },
315
+ idempotency_key=idempotency_key,
316
+ )
317
+
318
+ def record_not_attempted(
319
+ self,
320
+ *,
321
+ interaction_id: str,
322
+ reason_category: str,
323
+ expected_revision: int,
324
+ idempotency_key: str,
325
+ ) -> dict[str, Any]:
326
+ return self.complete_interaction(
327
+ interaction_id,
328
+ {
329
+ "kind": "not_attempted",
330
+ "outcomeClass": None,
331
+ "reasonCategory": reason_category,
332
+ "expectedRevision": expected_revision,
333
+ },
334
+ idempotency_key=idempotency_key,
335
+ )
@@ -0,0 +1,225 @@
1
+ """Opt-in M9.13 contribution flow for synchronous Python integrations.
2
+
3
+ An authorized caller owns the external action and explicit classification.
4
+ No background retries, automatic success inference, or network evidence minting.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import inspect
9
+ import re
10
+ from datetime import datetime
11
+ from collections.abc import Callable, Mapping
12
+ from types import MappingProxyType
13
+ from typing import Any
14
+
15
+ from .client import GenlavaApiError, GenlavaClient, _idempotency_key, _interaction_id
16
+
17
+ OUTCOME_CLASSES = (
18
+ "completed_as_intended", "partially_completed", "not_completed",
19
+ "cancelled_after_attempt", "indeterminate_after_attempt",
20
+ )
21
+ NON_ACTION_REASONS = (
22
+ "policy_declined", "caller_cancelled", "local_precondition_not_met",
23
+ "context_stale_or_superseded", "local_execution_unavailable",
24
+ "reason_not_available",
25
+ )
26
+
27
+
28
+ def _uncertain(stage: str, interaction_id: str, attempted: bool, error: Exception | None = None) -> dict[str, Any]:
29
+ return {
30
+ "state": "requires_reconciliation", "stage": stage,
31
+ "interactionId": interaction_id, "attempted": attempted,
32
+ "httpStatus": error.status if isinstance(error, GenlavaApiError) else None,
33
+ }
34
+
35
+
36
+ def _decision(value: Any, attempted: bool) -> dict[str, str]:
37
+ if not isinstance(value, dict) or type(value) is not dict:
38
+ raise TypeError("Explicit classification required")
39
+ kind = value.get("kind")
40
+ if kind == "outcome" and attempted and set(value) == {"kind", "outcomeClass"}:
41
+ outcome_class = value.get("outcomeClass")
42
+ if isinstance(outcome_class, str) and outcome_class in OUTCOME_CLASSES:
43
+ return {"kind": "outcome", "outcomeClass": outcome_class}
44
+ if kind == "not_attempted" and not attempted and set(value) == {"kind", "reasonCategory"}:
45
+ reason = value.get("reasonCategory")
46
+ if isinstance(reason, str) and reason in NON_ACTION_REASONS:
47
+ return {"kind": "not_attempted", "reasonCategory": reason}
48
+ raise TypeError("Classification conflicts with attempted action or canonical vocabulary")
49
+
50
+
51
+ def _valid_prepared_at(value: Any) -> bool:
52
+ """Reject calendar and timezone-normalized invalid RFC3339 timestamps."""
53
+ if type(value) is not str:
54
+ return False
55
+ matched = re.fullmatch(
56
+ r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?(Z|[+-]\d\d:\d\d)",
57
+ value, flags=re.ASCII,
58
+ )
59
+ if matched is None:
60
+ return False
61
+ # Some Python versions normalize 24:00:00 to the following day.
62
+ # Validate clock components explicitly before parsing, matching the JS SDK.
63
+ if int(value[11:13]) > 23 or int(value[14:16]) > 59 or int(value[17:19]) > 59:
64
+ return False
65
+ zone = matched.group(1)
66
+ # datetime.fromisoformat would silently normalize -00:60 to -01:00.
67
+ if zone != "Z" and (int(zone[1:3]) > 23 or int(zone[4:6]) > 59):
68
+ return False
69
+ try:
70
+ datetime.fromisoformat(value.replace("Z", "+00:00"))
71
+ except ValueError:
72
+ return False
73
+ return True
74
+
75
+
76
+ _ACTION_FIELDS = frozenset(("actionClass","effectClass","objectClass","scopeClass"))
77
+ _PREPARED_FIELDS = frozenset(("interactionId","actionCheckId","counterpartyId",
78
+ "action","targetRef","memoryCommitmentRef","preparedAt"))
79
+
80
+
81
+ def _prepared_bound(prepared: Any, requested: Mapping[str, Any]) -> str:
82
+ data = prepared.get("data") if isinstance(prepared, Mapping) else None
83
+ p = data.get("interaction") if isinstance(data, Mapping) else None
84
+ action = p.get("action") if isinstance(p, Mapping) else None
85
+ wanted = requested.get("action")
86
+ if (
87
+ type(p) is not dict or frozenset(p) != _PREPARED_FIELDS
88
+ or type(action) is not dict or frozenset(action) != _ACTION_FIELDS
89
+ or type(wanted) is not dict
90
+ or frozenset(wanted) != _ACTION_FIELDS
91
+ or any(action[field] != wanted[field] for field in _ACTION_FIELDS)
92
+ or p["counterpartyId"] != requested.get("counterpartyId")
93
+ or p["targetRef"] != requested.get("targetRef")
94
+ or p["memoryCommitmentRef"] != requested.get("memoryCommitmentRef")
95
+ or type(p["interactionId"]) is not str
96
+ or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{7,159}",p["interactionId"]) is None
97
+ or type(p["actionCheckId"]) is not str
98
+ or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{7,159}",p["actionCheckId"]) is None
99
+ or not _valid_prepared_at(p["preparedAt"])
100
+ ):
101
+ raise TypeError("Prepared interaction binding mismatch")
102
+ return p["interactionId"]
103
+
104
+
105
+ def _completion_acknowledged(completion: Any, interaction_id: str, expected_revision: int) -> bool:
106
+ # A transport 2xx and matching schemaVersion do not prove this specific
107
+ # terminal mutation was accepted. Never turn an ambiguous ack into success.
108
+ data = completion.get("data") if isinstance(completion, Mapping) else None
109
+ result = data.get("result") if isinstance(data, Mapping) else None
110
+ return (
111
+ isinstance(result, Mapping)
112
+ and result.get("interactionId") == interaction_id
113
+ and result.get("mutationKind") == "complete"
114
+ and result.get("terminal") is True
115
+ and type(result.get("revision")) is int
116
+ and result["revision"] == expected_revision + 1
117
+ )
118
+
119
+
120
+ def run_prepared_contribution(
121
+ *,
122
+ client: GenlavaClient,
123
+ prepare_input: Mapping[str, Any],
124
+ prepare_idempotency_key: str,
125
+ completion_idempotency_key: str,
126
+ expected_revision: int,
127
+ execute: Callable[[Mapping[str, Any]], Any],
128
+ classify: Callable[[Mapping[str, Any]], Mapping[str, str]],
129
+ ) -> dict[str, Any]:
130
+ """Prepare once, execute the caller action once, classify the actual outcome, then complete.
131
+
132
+ A post-prepare transport/side-effect uncertainty yields requires_reconciliation.
133
+ The caller must reuse the exact keys when reconciling; never replay an effect.
134
+ This helper never counts a completed operation as independent outcome evidence.
135
+ """
136
+ if not isinstance(client, GenlavaClient):
137
+ raise TypeError("GenlavaClient required")
138
+ if not isinstance(prepare_input, Mapping):
139
+ raise TypeError("prepare_input must be a mapping")
140
+ _idempotency_key(prepare_idempotency_key)
141
+ _idempotency_key(completion_idempotency_key)
142
+ if prepare_idempotency_key == completion_idempotency_key:
143
+ raise TypeError("Distinct mutations require distinct keys")
144
+ if type(expected_revision) is not int or expected_revision < 0:
145
+ raise TypeError("Explicit expected_revision required")
146
+ if not callable(execute) or not callable(classify):
147
+ raise TypeError("execute and classify callbacks required")
148
+ if inspect.iscoroutinefunction(execute) or inspect.iscoroutinefunction(classify):
149
+ raise TypeError("Use synchronous callbacks with the synchronous Python SDK")
150
+
151
+ # Capture caller intent before any potentially user-supplied transport can
152
+ # mutate its original request mapping while the response is outstanding.
153
+ action_input = prepare_input.get("action")
154
+ intended = {
155
+ "counterpartyId": prepare_input.get("counterpartyId"),
156
+ "action": {field: action_input.get(field) for field in _ACTION_FIELDS}
157
+ if isinstance(action_input, Mapping) else None,
158
+ "targetRef": prepare_input.get("targetRef"),
159
+ "memoryCommitmentRef": prepare_input.get("memoryCommitmentRef"),
160
+ }
161
+ prepared = client.prepare_interaction(prepare_input, idempotency_key=prepare_idempotency_key)
162
+ # Validate against the pre-transport snapshot, not the now-mutable input.
163
+ interaction_id = _prepared_bound(prepared, intended)
164
+
165
+ attempted = False
166
+ open_action = True
167
+
168
+ def mark_attempted() -> None:
169
+ nonlocal attempted
170
+ if not open_action or attempted:
171
+ raise TypeError("Action may be marked only once")
172
+ attempted = True
173
+
174
+ try:
175
+ execution_result = execute(MappingProxyType({
176
+ "interactionId": interaction_id, "markAttempted": mark_attempted
177
+ }))
178
+ if inspect.isawaitable(execution_result):
179
+ if inspect.iscoroutine(execution_result):
180
+ execution_result.close()
181
+ return _uncertain("execution", interaction_id, attempted)
182
+ except Exception:
183
+ return _uncertain("execution", interaction_id, attempted)
184
+ finally:
185
+ open_action = False
186
+
187
+ try:
188
+ classification = classify(MappingProxyType({
189
+ "interactionId": interaction_id, "attempted": attempted,
190
+ "executionResult": execution_result
191
+ }))
192
+ if inspect.isawaitable(classification):
193
+ if inspect.iscoroutine(classification):
194
+ classification.close()
195
+ return _uncertain("classification", interaction_id, attempted)
196
+ except Exception:
197
+ return _uncertain("classification", interaction_id, attempted)
198
+
199
+ try:
200
+ terminal = _decision(classification, attempted)
201
+ except (TypeError, ValueError):
202
+ return _uncertain("classification", interaction_id, attempted)
203
+ try:
204
+ if terminal["kind"] == "outcome":
205
+ completion = client.record_outcome(
206
+ interaction_id=interaction_id,
207
+ outcome_class=terminal["outcomeClass"],
208
+ expected_revision=expected_revision,
209
+ idempotency_key=completion_idempotency_key,
210
+ )
211
+ else:
212
+ completion = client.record_not_attempted(
213
+ interaction_id=interaction_id,
214
+ reason_category=terminal["reasonCategory"],
215
+ expected_revision=expected_revision,
216
+ idempotency_key=completion_idempotency_key,
217
+ )
218
+ if not _completion_acknowledged(completion, interaction_id, expected_revision):
219
+ return _uncertain("completion_acknowledgement", interaction_id, attempted)
220
+ return {
221
+ "state": "completed", "interactionId": interaction_id,
222
+ "attempted": attempted, "kind": terminal["kind"], "completion": completion,
223
+ }
224
+ except Exception as error:
225
+ return _uncertain("completion", interaction_id, attempted, error)
@@ -0,0 +1,123 @@
1
+ # GENERATED from packages/api-contracts/openapi/genlava-v1.json. DO NOT EDIT.
2
+ from typing import Any, Dict, List, Literal, Optional, TypedDict, Union
3
+
4
+ API_MAJOR = "v1"
5
+ CONTRACT_VERSION = "2026-10-06"
6
+ RELEASE_STATE = "implemented_not_deployed"
7
+ PRODUCTION_AUTHORIZED = False
8
+ CHECK_REQUEST_SCHEMA_VERSION = "genlava-api-check-request-v1"
9
+ CHECK_RESPONSE_SCHEMA_VERSION = "genlava-api-check-response-v1"
10
+ PREPARE_REQUEST_SCHEMA_VERSION = "genlava-api-interaction-prepare-request-v1"
11
+ PREPARE_RESPONSE_SCHEMA_VERSION = "genlava-api-interaction-prepare-response-v1"
12
+ COMPLETION_REQUEST_SCHEMA_VERSION = "genlava-api-interaction-completion-request-v1"
13
+ COMPLETION_RESPONSE_SCHEMA_VERSION = "genlava-api-interaction-completion-response-v1"
14
+ API_ERROR_SCHEMA_VERSION = "genlava-api-error-v1"
15
+ IDEMPOTENCY_KEY_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._~:/+\\\\-]{7,191}$"
16
+ OPERATIONS: Dict[str, Dict[str, str]] = {
17
+ "checkCounterparty": {"method": "POST", "path": "/v1/checks"},
18
+ "completeInteraction": {"method": "POST", "path": "/v1/interactions/{interactionId}/completion"},
19
+ "prepareInteraction": {"method": "POST", "path": "/v1/interactions"},
20
+ }
21
+
22
+ class _CounterpartyIdentifierInputRequired(TypedDict):
23
+ namespace: Literal["dns_host", "merchant_provider_id", "legal_entity_id", "marketplace_id", "package_coordinate", "repository_coordinate", "api_endpoint", "mcp_endpoint", "a2a_endpoint"]
24
+ value: str
25
+
26
+ class CounterpartyIdentifierInput(_CounterpartyIdentifierInputRequired, total=False):
27
+ authority: Optional[str]
28
+ class Action(TypedDict):
29
+ actionClass: Literal["inspect", "request", "invoke", "commit", "transfer", "fulfill"]
30
+ effectClass: Literal["read_only", "external_side_effect", "binding_commitment", "value_or_custody_transfer"]
31
+ objectClass: Literal["counterparty", "goods", "service", "capacity", "data", "shipment", "value", "access"]
32
+ scopeClass: Literal["counterparty", "capability", "resource"]
33
+ class _CheckRequestRequired(TypedDict):
34
+ schemaVersion: Literal["genlava-api-check-request-v1"]
35
+ identifier: CounterpartyIdentifierInput
36
+
37
+ class CheckRequest(_CheckRequestRequired, total=False):
38
+ action: Optional[Action]
39
+ effectiveAt: Optional[str]
40
+ taskCode: Optional[str]
41
+ contextRef: Optional[str]
42
+ class QueryExplanationItem(TypedDict):
43
+ schemaVersion: Literal["genlava-query-explanation-item-v1"]
44
+ layer: Literal["publicProviderIntelligence", "counterpartyAssertions", "organizationExperience", "independentNetworkMemory"]
45
+ provenanceClass: Literal["public_provider", "counterparty_declared", "caller_organization", "independent_network"]
46
+ provenanceRef: str
47
+ memoryRef: str
48
+ evidenceRef: str
49
+ counterpartyId: str
50
+ freshness: Literal["current", "stale", "expired", "unknown"]
51
+ actionKey: Optional[str]
52
+ selectionReason: Literal["query_scope", "generic_memory", "exact_action"]
53
+ conflictRefs: List[str]
54
+ lineageRefs: List[str]
55
+ class QueryExplanation(TypedDict):
56
+ schemaVersion: Literal["genlava-query-explanation-v1"]
57
+ identityState: Literal["no_candidate", "resolved", "ambiguous", "candidate_limit_exceeded"]
58
+ resolvedCounterpartyId: Optional[str]
59
+ identityProvenanceRefs: List[str]
60
+ selectionMode: Literal["exact_action_plus_generic", "query_scope_all"]
61
+ queryActionKey: Optional[str]
62
+ items: List[QueryExplanationItem]
63
+ conflictRefs: List[str]
64
+ lineageRefs: List[str]
65
+ insufficientData: List[Literal["identity_unresolved", "identity_ambiguous", "identity_candidate_limit", "no_evidence", "no_independent_memory", "all_evidence_stale", "conflicting_evidence"]]
66
+ class CheckResponse(TypedDict):
67
+ schemaVersion: Literal["genlava-api-check-response-v1"]
68
+ requestId: str
69
+ result: QueryExplanation
70
+ class _InteractionPrepareRequestRequired(TypedDict):
71
+ schemaVersion: Literal["genlava-api-interaction-prepare-request-v1"]
72
+ counterpartyId: str
73
+ action: Action
74
+
75
+ class InteractionPrepareRequest(_InteractionPrepareRequestRequired, total=False):
76
+ targetRef: Optional[str]
77
+ memoryCommitmentRef: Optional[str]
78
+ class InteractionPrepareResponseInteraction(TypedDict):
79
+ interactionId: str
80
+ actionCheckId: str
81
+ counterpartyId: str
82
+ action: Action
83
+ targetRef: Optional[str]
84
+ memoryCommitmentRef: Optional[str]
85
+ preparedAt: str
86
+ class InteractionPrepareResponse(TypedDict):
87
+ schemaVersion: Literal["genlava-api-interaction-prepare-response-v1"]
88
+ requestId: str
89
+ interaction: InteractionPrepareResponseInteraction
90
+ class _InteractionCompletionRequestRequired(TypedDict):
91
+ schemaVersion: Literal["genlava-api-interaction-completion-request-v1"]
92
+ kind: Literal["outcome", "not_attempted"]
93
+ expectedRevision: int
94
+
95
+ class InteractionCompletionRequest(_InteractionCompletionRequestRequired, total=False):
96
+ outcomeClass: Optional[Literal["completed_as_intended", "partially_completed", "not_completed", "cancelled_after_attempt", "indeterminate_after_attempt"]]
97
+ reasonCategory: Optional[Literal["policy_declined", "caller_cancelled", "local_precondition_not_met", "context_stale_or_superseded", "local_execution_unavailable", "reason_not_available"]]
98
+ class InteractionCompletionResponseResult(TypedDict):
99
+ interactionId: str
100
+ mutationKind: Literal["append_event", "complete"]
101
+ revision: int
102
+ terminal: bool
103
+ class InteractionCompletionResponse(TypedDict):
104
+ schemaVersion: Literal["genlava-api-interaction-completion-response-v1"]
105
+ requestId: str
106
+ result: InteractionCompletionResponseResult
107
+ class ApiErrorError(TypedDict):
108
+ code: Literal["invalid_request", "authentication_required", "authorization_denied", "not_found", "conflict", "idempotency_conflict", "rate_limited", "entitlement_required", "dependency_unavailable", "retryable_internal", "permanent_failure"]
109
+ message: str
110
+ requestId: str
111
+ retryable: bool
112
+ authenticationRequired: bool
113
+ authorizationRequired: bool
114
+ supportedVersion: Literal["v1"]
115
+ details: Optional[Dict[str, Any]]
116
+ class ApiError(TypedDict):
117
+ schemaVersion: Literal["genlava-api-error-v1"]
118
+ error: ApiErrorError
119
+ class CursorPage(TypedDict):
120
+ schemaVersion: Literal["genlava-api-page-v1"]
121
+ items: List[Any]
122
+ nextCursor: Optional[str]
123
+ hasMore: bool
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: genlava-sdk
3
+ Version: 0.1.0
4
+ Summary: Genlava API v1 client for Python
5
+ License-Expression: MIT
6
+ Project-URL: Documentation, https://genlava.com/docs/sdk
7
+ Project-URL: Homepage, https://genlava.com
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # Genlava SDK
14
+
15
+ Version 0.1.0 — API v1 client.
16
+
17
+ Documentation: https://genlava.com/docs/sdk
18
+
19
+ Use the explicit HTTPS origin https://api.genlava.com and your authorized, server-side Genlava API credential. Do not expose credentials in browser code. State-changing calls require stable idempotency keys.
20
+
21
+ Distribution and use are subject to the accompanying license. Registry publication and authenticated operation acceptance are independently verified.
@@ -0,0 +1,9 @@
1
+ genlava_sdk/__init__.py,sha256=lB-OElzpKIgOOyeYkH6fTY0eBkxqBigAL2oTXcJIG44,431
2
+ genlava_sdk/client.py,sha256=nkXtyLNigEi4XqZ1RKkpwifgnQerhll7t2HLSuVkYz4,12746
3
+ genlava_sdk/contribution.py,sha256=OhdbAqb88Lc2hBBRV7zQ6Qi8ykqHSqSg3ApHJkcGo00,10078
4
+ genlava_sdk/generated.py,sha256=CYKRtQUoZLxqeXCVSarGHcz94MMmbXkJWLo5VAObO2A,6184
5
+ genlava_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=AxC1qNVrCooOEHP7FBICI-eLtlJYelTktxazHims9ZU,1064
6
+ genlava_sdk-0.1.0.dist-info/METADATA,sha256=6tLTiYzO88oO114ZvfFSq2DWXouzv7fnyNvIMU9zeDA,782
7
+ genlava_sdk-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ genlava_sdk-0.1.0.dist-info/top_level.txt,sha256=Lw1XkN2WqIu3UaPTtG0WA3ytC1mVWeb58MY1RbCf_HQ,12
9
+ genlava_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Genlava
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ genlava_sdk