tauss-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.
@@ -0,0 +1,464 @@
1
+ """``tauss_client`` — a thin, synchronous HTTP client for the GammaLex API (ADR-007 §4, issue #19).
2
+
3
+ This module is always importable, even when ``httpx`` (a required dependency, imported
4
+ lazily) is not installed — ``from tauss_client import Gammx`` never raises on its own. Only
5
+ constructing a ``Gammx`` instance requires ``httpx``; if it is missing, ``Gammx(...)`` raises a
6
+ plain ``ImportError`` naming ``pip install tauss-client``, not a bare ``ModuleNotFoundError``
7
+ traceback (see ``client/tests/test_import_without_httpx.py``).
8
+
9
+ The client is intentionally thin: one ``httpx.Client``, one ``Authorization: Bearer <api_key>``
10
+ header set once at construction and never inspected, added to, or overridden per call (CLAUDE.md
11
+ invariant 8 — the SDK does not decide tenancy, it forwards whatever key the caller gives it), one
12
+ error path that turns every non-2xx response into :class:`~tauss_client.errors.GammxApiError` (or
13
+ its :class:`~tauss_client.errors.GammxAuthError` subclass for ``401``). No retries, no caching, no
14
+ business logic, no reasoning — the reasoning lives in Tauss core, reached only through the API
15
+ this client calls.
16
+
17
+ ``context()`` returns :class:`ContextResult`, a small frozen wrapper around the API's
18
+ ``{"run_id", "package"}`` 200 body (a 503 — ADR-018 — is a distinct shape, raised as
19
+ :class:`~tauss_client.errors.SourceUnavailableError` instead, never returned as a result).
20
+ ``get_run()`` returns :class:`RunResult`: ``GET /v1/runs/{id}`` answers one of two bodies
21
+ (ADR-018) — ``{"run_id", "package"}`` for a completed run, or ``{"run_id", "status":
22
+ "incomplete", "incomplete"}`` for one acquisition never finished — and ``RunResult`` carries
23
+ both a ``status`` (``"complete"``/``"incomplete"``) and whichever of ``package``/``incomplete``
24
+ the body actually had (the other is ``None``), so a caller that only ever read ``.package`` for
25
+ a complete run keeps working exactly as before. ``package``/``incomplete`` are plain ``dict``s
26
+ (the API's JSON bodies): this package never imports the engine, so it has no engine dataclasses
27
+ to rebuild them into.
28
+
29
+ ``record_decision``/``list_decisions`` call ``POST``/``GET /v1/decisions`` (ADR-006 §6, ADR-007
30
+ §2/§3, issue #18) — see the docstrings on those two methods below and ``api/README.md``,
31
+ "Decisions", for the exact request/response shapes and the ``subject`` filter.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from dataclasses import dataclass
37
+ from typing import TYPE_CHECKING, Any
38
+
39
+ from .drafts import DraftResult, DraftsMixin
40
+ from .errors import (
41
+ GammxApiError,
42
+ GammxAuthError,
43
+ IntentUnresolvedError,
44
+ RateLimitedError,
45
+ SourceUnavailableError,
46
+ )
47
+ from .evaluate import EvaluateMixin, EvaluationResult
48
+ from .integrations import (
49
+ IntegrationInfo,
50
+ SandboxIntegrationsMixin,
51
+ SandboxResult,
52
+ WorkspaceSettings,
53
+ )
54
+
55
+ if TYPE_CHECKING:
56
+ import httpx
57
+
58
+ __version__ = "0.1.0"
59
+
60
+ __all__ = [
61
+ "Gammx",
62
+ "__version__",
63
+ "ContextResult",
64
+ "RunResult",
65
+ "DraftResult",
66
+ "EvaluationResult",
67
+ "IntegrationInfo",
68
+ "SandboxResult",
69
+ "WorkspaceSettings",
70
+ "GammxApiError",
71
+ "GammxAuthError",
72
+ "IntentUnresolvedError",
73
+ "RateLimitedError",
74
+ "SourceUnavailableError",
75
+ ]
76
+
77
+
78
+ def _import_httpx() -> Any:
79
+ """Import ``httpx`` lazily, turning a missing install into a clear, actionable error."""
80
+ try:
81
+ import httpx
82
+ except ImportError as exc:
83
+ raise ImportError(
84
+ "tauss_client.Gammx requires httpx, which is not installed. Install it with "
85
+ "`pip install tauss-client`."
86
+ ) from exc
87
+ return httpx
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class ContextResult:
92
+ """A persisted run: its id plus the ``ContextPackage.to_dict()`` body (see module docstring)."""
93
+
94
+ run_id: str
95
+ package: dict[str, Any]
96
+ reused: bool = False
97
+ reused_from_run_id: str | None = None
98
+ reuse_reason: str | None = None
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class RunResult:
103
+ """``GET /v1/runs/{id}`` (see module docstring): ``status`` is ``"complete"`` or
104
+ ``"incomplete"`` (ADR-018); exactly one of ``package``/``incomplete`` is set, matching
105
+ ``status`` — the other is ``None``."""
106
+
107
+ run_id: str
108
+ status: str
109
+ package: dict[str, Any] | None
110
+ incomplete: dict[str, Any] | None
111
+
112
+
113
+ def _is_source_unavailable(response: httpx.Response) -> bool:
114
+ """Whether a ``503`` is the ADR-018 ``source_unavailable`` body (an incomplete run was
115
+ persisted), as opposed to a capacity ``503`` in the standard error envelope
116
+ (``database_busy``, ``acquisition_busy``) for which nothing was written."""
117
+ try:
118
+ data = response.json()
119
+ except ValueError:
120
+ return False
121
+ return isinstance(data, dict) and data.get("error") == "source_unavailable"
122
+
123
+
124
+ def _source_unavailable_error(response: httpx.Response) -> SourceUnavailableError:
125
+ """Build :class:`SourceUnavailableError` from a ``503 source_unavailable`` response body
126
+ (``{"error": "source_unavailable", "run_id", "sources", "retry_after"}`` — ADR-018). This
127
+ shape is deliberately not the standard ``{"error": {"code", "message", "request_id"}}``
128
+ envelope every other endpoint uses (``error`` is a string here, not an object), so it is
129
+ handled here rather than by :func:`_error_from_response`."""
130
+ data = response.json()
131
+ return SourceUnavailableError(
132
+ run_id=str(data.get("run_id", "")),
133
+ sources=list(data.get("sources", [])),
134
+ retry_after=int(data.get("retry_after", 0)),
135
+ )
136
+
137
+
138
+ def _error_from_response(response: httpx.Response) -> GammxApiError:
139
+ """Build the right :class:`GammxApiError` subclass from a non-2xx ``httpx.Response``."""
140
+ try:
141
+ error = response.json()["error"]
142
+ code = str(error["code"])
143
+ message = str(error["message"])
144
+ request_id = error.get("request_id")
145
+ candidates = error.get("candidates")
146
+ except (ValueError, KeyError, TypeError):
147
+ code, message, request_id, candidates = "unknown_error", response.text, None, None
148
+ if code == "intent_unresolved":
149
+ return IntentUnresolvedError(
150
+ response.status_code, code, message, request_id, candidates or []
151
+ )
152
+ if response.status_code == 429:
153
+ try:
154
+ retry_after = max(1, int(response.headers.get("Retry-After", "1")))
155
+ except ValueError:
156
+ retry_after = 1
157
+ return RateLimitedError(response.status_code, code, message, request_id, retry_after)
158
+ error_cls = GammxAuthError if response.status_code == 401 else GammxApiError
159
+ return error_cls(response.status_code, code, message, request_id)
160
+
161
+
162
+ class Gammx(SandboxIntegrationsMixin, EvaluateMixin, DraftsMixin):
163
+ """Synchronous client for the GammaLex API (``gammalex_api``, ADR-007 §3/§4).
164
+
165
+ Sandbox/integrations/workspace methods (``sandbox``, ``integrations``, ``connect``,
166
+ ``disconnect``, ``set_source_config``, ``workspace``, ``set_retention_mode``,
167
+ ``set_egress``) come from :class:`~tauss_client.integrations.SandboxIntegrationsMixin`, and
168
+ ``evaluate`` (ADR-026) from :class:`~tauss_client.evaluate.EvaluateMixin`, and
169
+ ``draft_bundle``/``approve_bundle`` (ADR-031) from :class:`~tauss_client.drafts.DraftsMixin`
170
+ (400-line ceiling).
171
+ """
172
+
173
+ def __init__(
174
+ self,
175
+ base_url: str,
176
+ api_key: str,
177
+ *,
178
+ timeout: float = 30.0,
179
+ _transport: Any = None,
180
+ ) -> None:
181
+ """``_transport`` is a private testing seam (an ``httpx.BaseTransport``, e.g.
182
+ ``httpx.MockTransport``) — not part of the public API, used only by this package's own
183
+ unit tests (``client/tests/test_decisions.py``, ``test_errors.py``) to exercise
184
+ request/response handling without a live server."""
185
+ httpx_module = _import_httpx()
186
+ self._client: httpx.Client = httpx_module.Client(
187
+ base_url=base_url.rstrip("/"),
188
+ timeout=timeout,
189
+ headers={"Authorization": f"Bearer {api_key}"},
190
+ transport=_transport,
191
+ )
192
+
193
+ def close(self) -> None:
194
+ """Close the underlying ``httpx.Client``. Safe to call more than once."""
195
+ self._client.close()
196
+
197
+ def __enter__(self) -> Gammx:
198
+ return self
199
+
200
+ def __exit__(self, *exc_info: object) -> None:
201
+ self.close()
202
+
203
+ def _request(self, method: str, path: str, **kwargs: Any) -> Any:
204
+ response = self._client.request(method, path, **kwargs)
205
+ return self._request_from_response(response)
206
+
207
+ def _request_from_response(self, response: httpx.Response) -> Any:
208
+ """The generic ``{"error": {code, message, request_id}}``/2xx handling every endpoint
209
+ but ``POST /v1/context``'s ``503`` uses — factored out so :meth:`context` can inspect
210
+ the raw response for that one endpoint-specific shape first (see
211
+ :func:`_source_unavailable_error`) while still reusing this for every other status."""
212
+ if response.status_code >= 400:
213
+ raise _error_from_response(response)
214
+ if response.status_code == 204 or not response.content:
215
+ return None
216
+ return response.json()
217
+
218
+ # -- health -------------------------------------------------------------------
219
+
220
+ def health(self) -> dict[str, Any]:
221
+ """``GET /v1/health``: liveness probe, no auth required by the server."""
222
+ return dict(self._request("GET", "/v1/health"))
223
+
224
+ # -- context / runs -------------------------------------------------------------
225
+
226
+ def context(
227
+ self,
228
+ *,
229
+ task: str | None = None,
230
+ actor: str,
231
+ scope: str | None = None,
232
+ intent: str | None = None,
233
+ request_id: str | None = None,
234
+ criteria: dict[str, Any] | None = None,
235
+ idempotency_key: str | None = None,
236
+ ) -> ContextResult:
237
+ """``POST /v1/context``: evaluate one Context Request and persist the result.
238
+
239
+ ``idempotency_key`` (ADR-028): sent as the ``Idempotency-Key`` header, so a retry or a
240
+ concurrent duplicate of the same call returns the run the key first produced instead of
241
+ creating another.
242
+
243
+ Either an explicit ``task``/``scope`` pair or a free-text ``intent`` must be given (item
244
+ 3, deterministic intent resolution) — mirrors ``ContextRequestBody`` on the server, which
245
+ resolves ``intent`` against the active bundle's own tasks only when ``task``/``scope``
246
+ are not both given; explicit ``task``/``scope`` always win when both are present, so this
247
+ method sends whatever it is given and lets the server apply that rule, rather than
248
+ re-implementing it here. Raises :class:`ValueError` if neither is given — a call that
249
+ would only ever fail on the server is refused before making the request.
250
+
251
+ ``criteria`` (caller evidence criteria, owner decision): ``{"must_contain": [str, ...],
252
+ "authority": str}``, both optional — the calling agent's own explicit statement of what
253
+ would count as evidence, checked deterministically by Tauss. Only meaningful together
254
+ with ``intent_scope`` synthesis (an ``intent`` naming no record reference); given
255
+ alongside an explicit ``task``/``scope`` or an ``intent`` that resolves to a record
256
+ reference, the server answers ``422 criteria_not_applicable`` rather than ignoring it —
257
+ this method sends whatever it is given and lets the server apply that rule.
258
+
259
+ Raises :class:`~tauss_client.errors.SourceUnavailableError` on a ``503`` (ADR-018):
260
+ acquisition could not complete because a source required for a necessary requirement was
261
+ UNAVAILABLE. No package was produced — ``GET /v1/runs/{run_id}`` (``get_run``) still
262
+ returns the persisted incomplete run. Raises
263
+ :class:`~tauss_client.errors.IntentUnresolvedError` on a ``422 intent_unresolved``:
264
+ ``intent`` did not resolve to exactly one ``{task, scope}`` — never a guess.
265
+ """
266
+ if intent is None and (task is None or scope is None):
267
+ raise ValueError(
268
+ "Gammx.context() requires either task and scope, or intent, to be given"
269
+ )
270
+ body: dict[str, Any] = {"actor": actor}
271
+ if task is not None:
272
+ body["task"] = task
273
+ if scope is not None:
274
+ body["scope"] = scope
275
+ if intent is not None:
276
+ body["intent"] = intent
277
+ if request_id is not None:
278
+ body["request_id"] = request_id
279
+ if criteria is not None:
280
+ body["criteria"] = criteria
281
+ headers = {"Idempotency-Key": idempotency_key} if idempotency_key is not None else None
282
+ response = self._client.request("POST", "/v1/context", json=body, headers=headers)
283
+ if response.status_code == 503 and _is_source_unavailable(response):
284
+ raise _source_unavailable_error(response)
285
+ data = self._request_from_response(response)
286
+ return ContextResult(
287
+ run_id=data["run_id"],
288
+ package=data["package"],
289
+ reused=bool(data.get("reused", False)),
290
+ reused_from_run_id=data.get("reused_from_run_id"),
291
+ reuse_reason=data.get("reuse_reason"),
292
+ )
293
+
294
+ def get_run(self, run_id: str) -> RunResult:
295
+ """``GET /v1/runs/{run_id}``: fetch a previously persisted run.
296
+
297
+ Returns a :class:`RunResult` whose ``status`` is ``"complete"`` (``package`` set,
298
+ ``incomplete`` ``None``) or ``"incomplete"`` (ADR-018: acquisition never finished for
299
+ this run — ``incomplete`` set, ``package`` ``None``). The server omits ``status``
300
+ entirely on a completed run's body, so its absence means ``"complete"``.
301
+ """
302
+ data = self._request("GET", f"/v1/runs/{run_id}")
303
+ status = data.get("status", "complete")
304
+ if status == "incomplete":
305
+ return RunResult(
306
+ run_id=data["run_id"],
307
+ status="incomplete",
308
+ package=None,
309
+ incomplete=data["incomplete"],
310
+ )
311
+ return RunResult(
312
+ run_id=data["run_id"], status="complete", package=data["package"], incomplete=None
313
+ )
314
+
315
+ def get_context_run(self, run_id: str) -> dict[str, Any]:
316
+ """``GET /v1/runs/{run_id}/context-run`` (Run v1, Step 1): the projected ``gammx.run/v1``
317
+ ``ContextRun`` for a previously persisted run, as a plain dict (``ContextRun.to_dict()``
318
+ JSON) -- no ``from_dict`` exists on that contract's client side yet, same rationale as
319
+ ``get_run()``'s ``package``/``incomplete`` (see the module docstring). ``404``
320
+ (``GammxApiError``) for an unknown run or another workspace's run."""
321
+ return dict(self._request("GET", f"/v1/runs/{run_id}/context-run"))
322
+
323
+ def list_runs(self, *, limit: int = 50, cursor: str | None = None) -> dict[str, Any]:
324
+ """``GET /v1/runs``: paginated run summaries, newest first."""
325
+ params: dict[str, Any] = {"limit": limit}
326
+ if cursor is not None:
327
+ params["cursor"] = cursor
328
+ return dict(self._request("GET", "/v1/runs", params=params))
329
+
330
+ def get_run_artifact(self, run_id: str) -> dict[str, Any]:
331
+ """``GET /v1/runs/{run_id}/artifact`` (ADR-018): the acquisition artifact of a
332
+ successful run — the exact merged record snapshot the kernel consumed, for offline
333
+ replay (``tauss replay``). ``404`` (``GammxApiError``) for an unknown run, another
334
+ workspace's run, or an incomplete run (no artifact was ever produced for it)."""
335
+ return dict(self._request("GET", f"/v1/runs/{run_id}/artifact"))
336
+
337
+ # -- bundle -----------------------------------------------------------------------
338
+
339
+ def put_bundle(self, yaml_text: str) -> dict[str, Any]:
340
+ """``PUT /v1/bundle`` (admin): upload a new bundle version. Does not activate it."""
341
+ return dict(
342
+ self._request(
343
+ "PUT",
344
+ "/v1/bundle",
345
+ content=yaml_text.encode("utf-8"),
346
+ headers={"Content-Type": "text/plain"},
347
+ )
348
+ )
349
+
350
+ def validate_bundle(self, yaml_text: str) -> dict[str, Any]:
351
+ """``POST /v1/bundle/validate`` (any role): check a bundle without storing it. Returns
352
+ ``{"ok", "errors", "summary"}``; an invalid bundle is ``ok: false`` with ``errors``, not
353
+ an exception."""
354
+ return dict(
355
+ self._request(
356
+ "POST",
357
+ "/v1/bundle/validate",
358
+ content=yaml_text.encode("utf-8"),
359
+ headers={"Content-Type": "text/plain"},
360
+ )
361
+ )
362
+
363
+ def activate_bundle(self, version: int) -> dict[str, Any]:
364
+ """``POST /v1/bundle/activate`` (admin): point the active bundle at ``version``."""
365
+ return dict(self._request("POST", "/v1/bundle/activate", json={"version": version}))
366
+
367
+ def get_bundle(self) -> dict[str, Any]:
368
+ """``GET /v1/bundle``: the currently active bundle's YAML text and version."""
369
+ return dict(self._request("GET", "/v1/bundle"))
370
+
371
+ def list_bundle_versions(self) -> dict[str, Any]:
372
+ """``GET /v1/bundle/versions``: every stored bundle version for this tenant --
373
+ ``{"versions": [{"version", "name", "active", "content_sha256", "created_at"}, ...]}``.
374
+ ``content_sha256`` is content-addressed (the bundle's own ``version:`` line blanked
375
+ before hashing, ``gammalex_api.services.bundles.content_sha256_of``), so a caller can
376
+ tell "this version number already exists" apart from "and its content matches what I
377
+ have" without a per-version read of the full ``yaml_text`` (no such endpoint exists --
378
+ only the currently *active* bundle's text is readable via :meth:`get_bundle`). Used by
379
+ ``scripts/pilot/seed_workspace.py`` to make a ``409`` from :meth:`put_bundle` safe
380
+ rather than silently swallowed.
381
+ """
382
+ return dict(self._request("GET", "/v1/bundle/versions"))
383
+
384
+ # -- records ----------------------------------------------------------------------
385
+
386
+ def push_records(
387
+ self, *, source_id: str, records: list[dict[str, Any]]
388
+ ) -> list[dict[str, Any]]:
389
+ """``POST /v1/records``: append one new version per record in the batch."""
390
+ result = self._request(
391
+ "POST", "/v1/records", json={"source_id": source_id, "records": records}
392
+ )
393
+ return list(result)
394
+
395
+ def list_records(
396
+ self, *, source_id: str | None = None, record_type: str | None = None
397
+ ) -> list[dict[str, Any]]:
398
+ """``GET /v1/records``: metadata (no ``content``) of the latest version of every record,
399
+ following ``next_cursor`` to the end."""
400
+ out: list[dict[str, Any]] = []
401
+ cursor: str | None = None
402
+ while True:
403
+ params: dict[str, Any] = {
404
+ "limit": 200,
405
+ "source_id": source_id,
406
+ "record_type": record_type,
407
+ }
408
+ if cursor:
409
+ params["cursor"] = cursor
410
+ page = self._request(
411
+ "GET", "/v1/records", params={k: v for k, v in params.items() if v}
412
+ )
413
+ out += list(page["records"])
414
+ cursor = page.get("next_cursor")
415
+ if not cursor:
416
+ return out
417
+
418
+ # -- keys (admin) --------------------------------------------------------------------
419
+
420
+ def create_key(self, *, role: str = "caller") -> dict[str, Any]:
421
+ """``POST /v1/keys`` (admin): create a new key in the caller's own workspace+environment."""
422
+ return dict(self._request("POST", "/v1/keys", json={"role": role}))
423
+
424
+ def list_keys(self) -> list[dict[str, Any]]:
425
+ """``GET /v1/keys`` (admin): the workspace keys: id, prefix, role, dates. No secrets."""
426
+ return list(self._request("GET", "/v1/keys")["keys"])
427
+
428
+ def revoke_key(self, key_id: str) -> dict[str, Any]:
429
+ """``POST /v1/keys/{key_id}/revoke`` (admin): revoke one key. Revoking twice is fine."""
430
+ return dict(self._request("POST", f"/v1/keys/{key_id}/revoke"))
431
+
432
+ # -- decisions --------------------------------------------------------------------
433
+ #
434
+ # POST/GET /v1/decisions (ADR-006 §6, ADR-007 §2/§3, issue #18) — see api/README.md,
435
+ # "Decisions", and api/gammalex_api/routes/decisions.py for the exact contract these two
436
+ # methods wrap. A decision is a record of the active bundle's declared decision
437
+ # `record_type` (default `"decision"`); the request body is `{subject, statement,
438
+ # decided_by, decided_at, relied_on, decision_id?}` (ADR-006 §2) — `decision_id` is optional,
439
+ # server-generated (`uuid4()`) when omitted, and becomes the written record's `natural_key`.
440
+
441
+ def record_decision(self, decision: dict[str, Any]) -> dict[str, Any]:
442
+ """``POST /v1/decisions``: record one decision.
443
+
444
+ ``decision`` is ``{subject, statement, decided_by, decided_at, relied_on, decision_id?}``
445
+ (see the section note above). Returns ``{decision_id, record_type, version_seq}``.
446
+ """
447
+ return dict(self._request("POST", "/v1/decisions", json=decision))
448
+
449
+ def list_decisions(
450
+ self, *, subject: str | None = None, limit: int = 50, cursor: str | None = None
451
+ ) -> dict[str, Any]:
452
+ """``GET /v1/decisions``: paginated decisions, optionally filtered by ``subject``.
453
+
454
+ Returns ``{"decisions": [{"decision_id": ..., <declared decision fields>}, ...],
455
+ "next_cursor": ...}`` — each row is that decision's latest version only, newest
456
+ ``retrieved_at`` first. An empty result is ``{"decisions": [], "next_cursor": None}``,
457
+ never a 404 (a workspace with no decisions posted is a valid, empty answer).
458
+ """
459
+ params: dict[str, Any] = {"limit": limit}
460
+ if subject is not None:
461
+ params["subject"] = subject
462
+ if cursor is not None:
463
+ params["cursor"] = cursor
464
+ return dict(self._request("GET", "/v1/decisions", params=params))