commitlayer 0.1.0__py3-none-any.whl → 0.1.3__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.
commitlayer/__init__.py CHANGED
@@ -16,6 +16,11 @@ never changes what the function returns. Recording failures are logged and swall
16
16
  an action that was never recorded rather than one that never happened. Set ``fail_open=False`` to raise.
17
17
 
18
18
  Verification itself is done by the API from the systems of record; nothing here consults the function's result.
19
+
20
+ A request the API answers with 429 or 503 **and** a ``Retry-After`` header is sent again after the wait the
21
+ header states: ``max_retries`` times at most (default 3, ``0`` turns it off), and only when the wait is no longer
22
+ than ``max_retry_wait`` seconds (default 10). No other answer is retried, and neither is a timeout or a network
23
+ error. See ``Client`` and the README.
19
24
  """
20
25
 
21
26
  from __future__ import annotations
@@ -23,31 +28,145 @@ from __future__ import annotations
23
28
  import functools
24
29
  import json
25
30
  import logging
31
+ import math
26
32
  import os
33
+ import posixpath
34
+ import random
35
+ import re
27
36
  import time
28
37
  import urllib.error
38
+ import urllib.parse
29
39
  import urllib.request
30
40
  import uuid
31
- from collections.abc import Callable
32
- from datetime import UTC, datetime
41
+ from collections.abc import Callable, Iterable, Mapping
42
+ from datetime import datetime, timezone
43
+ from email.utils import parsedate_to_datetime
33
44
  from typing import Any
34
45
 
35
- __all__ = ["Client", "CommitLayerError", "__version__"]
36
- __version__ = "0.1.0"
46
+ __all__ = ["Client", "CommitLayerError", "Packs", "__version__"]
47
+ __version__ = "0.1.3" # kept equal to pyproject.toml; tests check it
37
48
 
38
49
  log = logging.getLogger("commitlayer")
39
50
 
40
- Transport = Callable[[str, str, dict[str, Any] | None], tuple[int, dict[str, Any]]]
51
+ # A transport sends one request and returns ``(status, payload)`` or ``(status, payload, headers)``, where
52
+ # ``headers`` holds the response headers: a mapping, the headers object ``urllib`` and ``http.client`` give
53
+ # (``response.headers``), or a list of ``(name, value)`` pairs. A transport that returns no headers never causes
54
+ # a retry: the wait is read from ``Retry-After`` and from nowhere else.
55
+ Headers = Mapping[str, Any] | Iterable[tuple[Any, Any]]
56
+ Transport = Callable[
57
+ [str, str, dict[str, Any] | None],
58
+ tuple[int, dict[str, Any]] | tuple[int, dict[str, Any], Headers],
59
+ ]
60
+
61
+ RETRY_STATUSES = (429, 503)
62
+ # The random addition to a wait is at most this many times the stated wait, so a burst refused together comes
63
+ # back spread over that time: a wait of one stated second is between one and three. The API admits a few writes
64
+ # of one workspace at a time and refuses the rest at once, so calls that return within the same fraction of a
65
+ # second are mostly refused together again; spread over two seconds they are admitted as they arrive.
66
+ _RETRY_SPREAD = 2.0
67
+ _DELTA_SECONDS = re.compile(r"[0-9]+(?:\.[0-9]*)?|\.[0-9]+")
41
68
 
42
69
 
43
70
  class CommitLayerError(RuntimeError):
44
- def __init__(self, status: int, code: str, message: str, details: Any = None):
71
+ """An answer of 400 or above. ``retry_after`` is the wait its ``Retry-After`` header stated, in seconds, or
72
+ ``None`` when it stated none the client could read; ``attempts`` is how many times the request was sent."""
73
+
74
+ def __init__(
75
+ self,
76
+ status: int,
77
+ code: str,
78
+ message: str,
79
+ details: Any = None,
80
+ *,
81
+ retry_after: float | None = None,
82
+ attempts: int = 1,
83
+ ):
45
84
  super().__init__(f"{code} ({status}): {message}")
46
85
  self.status, self.code, self.message, self.details = status, code, message, details
86
+ self.retry_after, self.attempts = retry_after, attempts
87
+
88
+ def __reduce__(self) -> tuple[Any, ...]:
89
+ # An exception is rebuilt from its ``args``, which here is the one formatted message; give the
90
+ # constructor its own parameters back so the error can be pickled and copied (a process pool does both).
91
+ return type(self), (self.status, self.code, self.message, self.details), dict(vars(self))
47
92
 
48
93
 
49
94
  def _now() -> str:
50
- return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
95
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
96
+
97
+
98
+ def _header_values(headers: Any, name: str) -> list[Any]:
99
+ """Every value of one response header, whatever the case of its name. ``headers`` is a mapping, any object
100
+ with ``items()`` (``http.client.HTTPMessage``, which can hold a name twice) or an iterable of
101
+ ``(name, value)`` pairs; a name may be ``str`` or ``bytes``. Anything else is no headers at all."""
102
+ if headers is None:
103
+ return []
104
+ found = []
105
+ try:
106
+ for key, value in headers.items() if hasattr(headers, "items") else headers:
107
+ if isinstance(key, (bytes, bytearray)):
108
+ key = key.decode("latin-1")
109
+ if isinstance(key, str) and key.lower() == name:
110
+ found.append(value)
111
+ except (TypeError, ValueError): # not headers: a number, a string, items that are not pairs
112
+ return []
113
+ return found
114
+
115
+
116
+ def _header(headers: Any, name: str) -> Any:
117
+ """One response header, whatever the case of its name; ``None`` when absent or when there are no headers."""
118
+ values = _header_values(headers, name)
119
+ return values[0] if values else None
120
+
121
+
122
+ def _stated_wait(headers: Any, now: datetime | None = None) -> float | None:
123
+ """The wait the answer's ``Retry-After`` states, in seconds, or ``None`` when it states none the client can
124
+ read. An answer that carries the header twice (a proxy added its own) is taken at the longer wait."""
125
+ waits = [w for w in (_parse_retry_after(v, now) for v in _header_values(headers, "retry-after")) if w is not None]
126
+ return max(waits) if waits else None
127
+
128
+
129
+ def _parse_retry_after(value: Any, now: datetime | None = None) -> float | None:
130
+ """The seconds a ``Retry-After`` header asks for: delta-seconds (an integer or a decimal, zero or more) or
131
+ an HTTP-date, measured from ``now``; a date already past is zero. ``None`` when the header is absent or is
132
+ anything else (negative, a word, an exponent, more digits than a number holds), which the client treats as
133
+ no stated wait at all."""
134
+ if value is None:
135
+ return None
136
+ if isinstance(value, (bytes, bytearray)):
137
+ value = value.decode("latin-1")
138
+ text = str(value).strip()
139
+ if _DELTA_SECONDS.fullmatch(text):
140
+ seconds = float(text)
141
+ return seconds if math.isfinite(seconds) else None
142
+ try:
143
+ when = parsedate_to_datetime(text)
144
+ except (TypeError, ValueError, IndexError, OverflowError):
145
+ return None
146
+ if when.tzinfo is None:
147
+ when = when.replace(tzinfo=timezone.utc)
148
+ try:
149
+ return max(0.0, (when - (now or datetime.now(timezone.utc))).total_seconds())
150
+ except OverflowError:
151
+ return None
152
+
153
+
154
+ def _repeatable(method: str, path: str, body: Any) -> bool:
155
+ """Whether sending the request again can never record a second action. Recording is idempotent on
156
+ ``action_id``, and the API may answer 503 ``busy`` to ``POST /v1/actions`` after the action itself is stored
157
+ (its verification then runs in the background). A recording that names no ``action_id`` would be given a
158
+ new one by the API on every attempt, so it is never sent twice. ``record_action`` always names one; a raw
159
+ ``request`` and an inline ``verify`` carry whatever the caller wrote."""
160
+ if method.upper() != "POST" or not isinstance(body, dict):
161
+ return True
162
+ # The route as the server will read it: without query or fragment, percent-decoded, and with ``//``,
163
+ # ``/./`` and a trailing slash folded away, so another spelling of the same path is the same route.
164
+ route = posixpath.normpath("/" + urllib.parse.unquote(re.split(r"[?#]", path, maxsplit=1)[0]).lstrip("/"))
165
+ if route == "/v1/actions":
166
+ return bool(body.get("action_id"))
167
+ if route == "/v1/actions/verify" and isinstance(body.get("action"), dict) and not body.get("dry_run"):
168
+ return bool(body["action"].get("action_id"))
169
+ return True
51
170
 
52
171
 
53
172
  class Client:
@@ -59,20 +178,41 @@ class Client:
59
178
  timeout: float = 20.0,
60
179
  transport: Transport | None = None,
61
180
  agent_id: str | None = None,
181
+ max_retries: int = 3,
182
+ max_retry_wait: float = 10.0,
183
+ sleep: Callable[[float], None] = time.sleep,
184
+ jitter: Callable[[], float] = random.random,
62
185
  ):
186
+ """``max_retries`` is how many times a request answered 429 or 503 with a ``Retry-After`` header is sent
187
+ again (``0``: never). ``max_retry_wait`` is the longest stated wait, in seconds, the client accepts: a
188
+ longer one is not waited and the error is raised at once. The waits of one call therefore add up to at
189
+ most ``max_retries * max_retry_wait`` seconds. ``sleep`` does the waiting and ``jitter`` returns a number
190
+ in ``[0, 1)`` that spreads the waits (``0`` is the stated wait, ``1`` three times it or the ceiling,
191
+ whichever is less; anything else adds nothing); both exist for tests and for callers with their own
192
+ clock."""
193
+ if not (0 <= max_retries < math.inf and 0 <= max_retry_wait < math.inf): # also false for NaN
194
+ raise ValueError("max_retries and max_retry_wait must be numbers, zero or more")
63
195
  self.api_key = api_key or os.environ.get("COMMITLAYER_API_KEY") or ""
64
196
  self.api_url = (
65
197
  api_url or os.environ.get("COMMITLAYER_API_URL") or "https://api.commitlayer.ai"
66
198
  ).rstrip("/")
67
199
  self.timeout = timeout
68
200
  self.agent_id = agent_id
201
+ self.max_retries = int(max_retries)
202
+ self.max_retry_wait = float(max_retry_wait)
203
+ self._sleep = sleep
204
+ self._jitter = jitter
69
205
  self._transport = transport or self._http
70
206
  if not self.api_key and transport is None:
71
207
  raise ValueError("api_key is required (or set COMMITLAYER_API_KEY)")
72
208
 
73
209
  # ---------------- transport ----------------
74
210
 
75
- def _http(self, method: str, path: str, body: dict[str, Any] | None) -> tuple[int, dict[str, Any]]:
211
+ def _http(
212
+ self, method: str, path: str, body: dict[str, Any] | None
213
+ ) -> tuple[int, dict[str, Any], list[tuple[str, str]]]:
214
+ """One request over ``urllib``. The headers come back as ``(name, value)`` pairs, every one of them: a
215
+ name the answer carries twice is there twice."""
76
216
  data = json.dumps(body).encode() if body is not None else None
77
217
  req = urllib.request.Request(
78
218
  self.api_url + path,
@@ -88,26 +228,76 @@ class Client:
88
228
  try:
89
229
  with urllib.request.urlopen(req, timeout=self.timeout) as r: # noqa: S310 - fixed https host
90
230
  raw = r.read()
91
- return r.status, (json.loads(raw) if raw else {})
231
+ return r.status, (json.loads(raw) if raw else {}), r.headers.items()
92
232
  except urllib.error.HTTPError as e:
93
233
  raw = e.read()
234
+ headers = e.headers.items() if e.headers is not None else []
94
235
  try:
95
- return e.code, json.loads(raw) if raw else {}
236
+ return e.code, (json.loads(raw) if raw else {}), headers
96
237
  except ValueError:
97
- return e.code, {
98
- "error": {"code": "http_error", "message": raw.decode(errors="replace")[:300]}
99
- }
238
+ return (
239
+ e.code,
240
+ {"error": {"code": "http_error", "message": raw.decode(errors="replace")[:300]}},
241
+ headers,
242
+ )
100
243
 
101
244
  def _call(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
102
- status, payload = self._transport(method, path, body)
103
- if status >= 400:
245
+ """Send the request and return the payload, or raise ``CommitLayerError`` for an answer of 400 or above.
246
+
247
+ An answer of 429 or 503 that carries a ``Retry-After`` no longer than ``max_retry_wait`` is waited out
248
+ and the same request, with the same body, is sent again, ``max_retries`` times at most; after that the
249
+ last answer is the error. Nothing else is retried: not another status, not a 429 or 503 without the
250
+ header, and not a timeout or a network error, after which nobody knows whether the request arrived."""
251
+ attempts = 0
252
+ while True:
253
+ attempts += 1
254
+ answer = self._transport(method, path, body)
255
+ status, payload = answer[0], answer[1]
256
+ if status < 400:
257
+ return payload
258
+ retry_after = _stated_wait(answer[2] if len(answer) > 2 else None)
104
259
  err = payload.get("error") if isinstance(payload, dict) else None
105
260
  if isinstance(err, dict):
106
- raise CommitLayerError(
107
- status, err.get("code", "error"), err.get("message", ""), err.get("details")
261
+ error = CommitLayerError(
262
+ status,
263
+ err.get("code", "error"),
264
+ err.get("message", ""),
265
+ err.get("details"),
266
+ retry_after=retry_after,
267
+ attempts=attempts,
108
268
  )
109
- raise CommitLayerError(status, "error", str(payload)[:300])
110
- return payload
269
+ else:
270
+ error = CommitLayerError(
271
+ status, "error", str(payload)[:300], retry_after=retry_after, attempts=attempts
272
+ )
273
+ if (
274
+ attempts > self.max_retries
275
+ or status not in RETRY_STATUSES
276
+ or retry_after is None
277
+ or retry_after > self.max_retry_wait
278
+ or not _repeatable(method, path, body)
279
+ ):
280
+ raise error
281
+ # Never less than the server stated and never more than the ceiling, so the bound holds exactly: the
282
+ # addition is a random share of twice the stated wait, or of what is left under the ceiling when
283
+ # that is less.
284
+ try:
285
+ spread = float(self._jitter())
286
+ except (TypeError, ValueError):
287
+ spread = 0.0
288
+ room = min(retry_after * _RETRY_SPREAD, self.max_retry_wait - retry_after)
289
+ wait = retry_after + (room * spread if 0.0 <= spread <= 1.0 else 0.0)
290
+ log.info(
291
+ "commitlayer: %s %s answered %s %s; sending it again in %.2f s (retry %d of %d)",
292
+ method,
293
+ path.split("?", 1)[0],
294
+ status,
295
+ error.code,
296
+ wait,
297
+ attempts,
298
+ self.max_retries,
299
+ )
300
+ self._sleep(wait)
111
301
 
112
302
  # ---------------- actions and facts ----------------
113
303
 
@@ -175,7 +365,8 @@ class Client:
175
365
  links: list[dict[str, Any]] | None = None,
176
366
  dry_run: bool = False,
177
367
  ) -> dict[str, Any]:
178
- """``POST /v1/actions/verify``: verify now, by id or inline. ``dry_run`` stores nothing."""
368
+ """``POST /v1/actions/verify``: verify now, by id or inline. ``dry_run`` stores nothing. An inline
369
+ ``action`` that is stored and names no ``action_id`` is sent once only, never retried."""
179
370
  body: dict[str, Any] = {"dry_run": dry_run}
180
371
  if action_id:
181
372
  body["action_id"] = action_id
@@ -194,7 +385,9 @@ class Client:
194
385
  """The completion gate: block until the action's verdict settles or ``timeout`` seconds pass, and return
195
386
  the verification (``status`` is ``settled`` or, on timeout, ``pending``; ``timed_out`` says which). The
196
387
  API holds each call for up to 60 seconds; this loops. A workflow should not tell the customer "done"
197
- before this returns a settled PASS; FAIL routes to recovery; a timeout is the workflow's decision."""
388
+ before this returns a settled PASS; FAIL routes to recovery; a timeout is the workflow's decision.
389
+ A poll the API refuses with ``Retry-After`` is retried like any other request, which can add up to
390
+ ``max_retries * max_retry_wait`` seconds to ``timeout``."""
198
391
  deadline = time.monotonic() + max(0.0, timeout)
199
392
  while True:
200
393
  budget = max(0.0, min(60.0, deadline - time.monotonic()))
@@ -203,7 +396,8 @@ class Client:
203
396
  return v
204
397
 
205
398
  def request(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
206
- """Any endpoint, with the client's auth and error handling."""
399
+ """Any endpoint, with the client's auth, error handling and retries. A ``POST /v1/actions`` body
400
+ without an ``action_id`` is sent once only: the API would record a new action on every attempt."""
207
401
  return self._call(method, path, body)
208
402
 
209
403
  # ---------------- contracts ----------------
@@ -241,6 +435,15 @@ class Client:
241
435
  last one."""
242
436
  return self._call("POST", "/v1/contracts", {"yaml": yaml_text})
243
437
 
438
+ # ---------------- workflow packs ----------------
439
+
440
+ @property
441
+ def packs(self) -> Packs:
442
+ """The workflow packs (``/v1/packs``): ``client.packs.list()``, ``get``, ``configure``, ``dry_run``,
443
+ ``install``. Install creates drafts and never activates; activation stays a person's
444
+ ``POST /v1/contracts/{id}/select``."""
445
+ return Packs(self)
446
+
244
447
  # ---------------- decorator ----------------
245
448
 
246
449
  def action(
@@ -304,3 +507,55 @@ class Client:
304
507
  return wrapper
305
508
 
306
509
  return deco
510
+
511
+
512
+ class Packs:
513
+ """``/v1/packs``: the workflow pack library. Reads take any member; ``configure`` and ``dry_run`` write nothing
514
+ and take an analyst; ``install`` saves the configured contracts as **drafts** (never activates) and needs
515
+ ``confirm=True``. ``configuration`` is ``{workflow_id: {parameter_key: value}}``."""
516
+
517
+ def __init__(self, client: Client):
518
+ self._c = client
519
+
520
+ def list(self) -> dict[str, Any]:
521
+ """``GET /v1/packs``: ``{items: PackSummary[]}``."""
522
+ return self._c._call("GET", "/v1/packs")
523
+
524
+ def get(self, pack_id: str) -> dict[str, Any]:
525
+ """``GET /v1/packs/{id}``: the summary plus contracts, recorder mapping, fixtures, templates, readme,
526
+ versions and the workspace's requirements (plan, connectors, evidence)."""
527
+ return self._c._call("GET", f"/v1/packs/{pack_id}")
528
+
529
+ def configure(self, pack_id: str, configuration: dict[str, Any] | None = None) -> dict[str, Any]:
530
+ """``POST /v1/packs/{id}/configure``: the contracts with the configuration applied, the values in force and
531
+ every way a value weakens a check. Nothing is written."""
532
+ return self._c._call("POST", f"/v1/packs/{pack_id}/configure", {"configuration": configuration or {}})
533
+
534
+ def dry_run(
535
+ self, pack_id: str, configuration: dict[str, Any] | None = None, *, workflow: str | None = None
536
+ ) -> dict[str, Any]:
537
+ """``POST /v1/packs/{id}/dry-run``: every fixture case through the engine against the configured
538
+ contracts, in a savepoint; ``{summary: {total, ok}, cases: [...]}``. Nothing persists."""
539
+ body: dict[str, Any] = {"configuration": configuration or {}}
540
+ if workflow:
541
+ body["workflow"] = workflow
542
+ return self._c._call("POST", f"/v1/packs/{pack_id}/dry-run", body)
543
+
544
+ def install(
545
+ self, pack_id: str, configuration: dict[str, Any] | None = None, *, confirm: bool = False
546
+ ) -> dict[str, Any]:
547
+ """``POST /v1/packs/{id}/install``: save the configured contracts as drafts and record the installation.
548
+ Refused without ``confirm=True``; answers 402 ``plan_required`` below the pack's minimum plan. Returns
549
+ the drafts' versions, the recorder mapping with those versions pinned and the activation steps."""
550
+ return self._c._call(
551
+ "POST", f"/v1/packs/{pack_id}/install", {"configuration": configuration or {}, "confirm": confirm}
552
+ )
553
+
554
+ def coverage(self, pack_id: str) -> dict[str, Any]:
555
+ """``GET /v1/packs/{id}/coverage``: sources covered and their trust, unmapped consequential tools,
556
+ activation state per contract, identity links seen."""
557
+ return self._c._call("GET", f"/v1/packs/{pack_id}/coverage")
558
+
559
+ def recorder_mapping(self, pack_id: str) -> dict[str, Any]:
560
+ """``GET /v1/packs/{id}/recorder-mapping``: the installed mapping, contract versions pinned."""
561
+ return self._c._call("GET", f"/v1/packs/{pack_id}/recorder-mapping")
@@ -0,0 +1,212 @@
1
+ Metadata-Version: 2.4
2
+ Name: commitlayer
3
+ Version: 0.1.3
4
+ Summary: CommitLayer Python SDK: record agent actions, push facts, read verdicts, draft contracts
5
+ Author-email: "Asterfold Labs, Inc." <hello@commitlayer.ai>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://commitlayer.ai
8
+ Project-URL: Documentation, https://commitlayer.ai/docs
9
+ Project-URL: Changelog, https://commitlayer.ai/changelog
10
+ Project-URL: Source, https://github.com/commitlayer/commitlayer/tree/main/sdk/python
11
+ Keywords: ai-agents,verification,audit,mcp,observability
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # commitlayer (Python)
26
+
27
+ Record agent actions, push facts from systems of record, read verdicts and draft contracts. Standard library
28
+ only; Python 3.10+.
29
+
30
+ ```bash
31
+ pip install commitlayer
32
+ export COMMITLAYER_API_KEY=spk_... # the agent runtime's key: a *recorder* key (records actions, nothing else)
33
+ export COMMITLAYER_EVIDENCE_KEY=spk_... # the pipeline's key: an *evidence* key bound to the sources it pushes for
34
+ # COMMITLAYER_API_URL defaults to https://api.commitlayer.ai. One credential per side of the line: the key that
35
+ # records an action can never also supply the facts that verify it.
36
+ ```
37
+
38
+ ## Record an action where it happens
39
+
40
+ ```python
41
+ from commitlayer import Client
42
+
43
+ cl = Client(agent_id="support-bot")
44
+
45
+
46
+ @cl.action(
47
+ "refund_workflow",
48
+ subject=lambda order_id, **_: order_id,
49
+ params=lambda amount, **_: {"amount": amount},
50
+ subject_kind="order",
51
+ action_id=lambda order_id, **_: f"refund:{order_id}", # retries update one claim instead of recording two
52
+ )
53
+ def refund(order_id: str, amount: float) -> dict:
54
+ return payments.refund(order_id, amount) # the agent's own work, unchanged
55
+
56
+
57
+ refund("order_10231", 180.0)
58
+ print(refund.last_recorded["verification"]["summary"]["headline"])
59
+ ```
60
+
61
+ The action is recorded **before** the function runs, so its request time precedes every effect. The function's
62
+ return value is never changed and never consulted: verification reads the systems of record. If the API cannot
63
+ be reached the function still runs and a warning is logged (`fail_open=True`); pass `fail_open=False` to raise.
64
+
65
+ ## Push facts, with a watermark
66
+
67
+ Use an **evidence** key here, bound to the sources it pushes for (Settings → API keys). The key your agent runtime records actions with is a **recorder** key and cannot push facts: the credential that records an action never also supplies the facts that verify it.
68
+
69
+ ```python
70
+ import os
71
+
72
+ evidence = Client(api_key=os.environ["COMMITLAYER_EVIDENCE_KEY"]) # the pipeline's own client, not the runtime's
73
+
74
+ evidence.push_facts(
75
+ [
76
+ {
77
+ "source": "crm",
78
+ "subject_id": "order_10231",
79
+ "fact_type": "note_added",
80
+ "occurred_at": "2026-10-13T10:42:09Z",
81
+ }
82
+ ],
83
+ watermarks={"crm": "2026-10-13T10:45:00Z"}, # everything up to here has been sent for crm
84
+ )
85
+ ```
86
+
87
+ A verdict that is not yet a PASS settles only when its window has closed **and** every source it reads has a
88
+ watermark past the end of the window. Declare one when your feed lags; a source that never declares one is taken
89
+ as current.
90
+
91
+ ## Draft a contract from what was recorded
92
+
93
+ ```python
94
+ d = cl.draft_contract("refund_order", lookback_days=30)
95
+ print(d["yaml"]) # expected effects, window, preconditions, limits, from the sample
96
+ print(d["stats"]["effects"])
97
+ v = cl.validate_contract(d["yaml"]) # errors, and weakening warnings against the version it would replace
98
+ cl.save_contract(d["yaml"]) # the response carries the same warnings
99
+ ```
100
+
101
+ Every value in a draft is what the sample showed, not what the policy says. Review it before saving.
102
+
103
+ ## Read a verdict
104
+
105
+ ```python
106
+ v = cl.get_action("refund:order_10231")
107
+ v["status"] # pending | settled
108
+ v["settlement"]["waiting_on"] # sources still behind the window, if any
109
+ v["reversal"] # the later record that undid the action, if any
110
+ v["sources"] # trust level and watermark per source the contract read
111
+ ```
112
+
113
+ ## Wait for the verdict before saying "done"
114
+
115
+ ```python
116
+ v = cl.wait_for_settlement("refund:order_10231", timeout=300) # blocks until settled or 5 minutes
117
+ if v["timed_out"]:
118
+ ... # still pending: your policy, never "success"
119
+ elif v["lenses"]["outcome"]["verdict"] == "PASS":
120
+ notify_customer("Your order is cancelled and refunded.")
121
+ else:
122
+ open_recovery(v) # FAIL: the reasons name what is missing or forbidden
123
+ ```
124
+
125
+ The API holds each call for up to 60 seconds; the SDK loops. The gate reads evidence; it never changes a verdict.
126
+
127
+ ## Install a workflow pack (drafts, never activation)
128
+
129
+ ```python
130
+ packs = cl.packs.list()["items"] # Stripe Customer Operations, x402, Coinbase
131
+ detail = cl.packs.get("stripe_customer_operations") # contracts, requirements, templates, versions
132
+ effective = cl.packs.configure("stripe_customer_operations", {"refund_order": {"approved_limit": 100}})
133
+ report = cl.packs.dry_run("stripe_customer_operations", {"refund_order": {"approved_limit": 100}})
134
+ assert report["summary"]["ok"] == report["summary"]["total"] # every fixture case holds under your limits
135
+ out = cl.packs.install("stripe_customer_operations", {"refund_order": {"approved_limit": 100}}, confirm=True)
136
+ print(out["activation"]["how"]) # POST /v1/contracts/<id>/select, by a person
137
+ mapping = cl.packs.recorder_mapping("stripe_customer_operations") # contract versions pinned
138
+ ```
139
+
140
+ `configure` and `dry_run` write nothing. `install` saves the configured contracts as **drafts**: nothing governs a
141
+ live action until a person activates a version in the app or with `POST /v1/contracts/{id}/select`. Below the
142
+ pack's minimum plan the service answers `402 plan_required` with `upgrade_to`.
143
+
144
+ ## What is retried
145
+
146
+ When the API cannot admit a request it answers `503 busy` (the service is at its limit) or `429` (`workspace_busy`:
147
+ this workspace already has its share of writes in progress; `rate_limited`: its requests a minute are spent) with a
148
+ `Retry-After` header. The client waits the time the header states and sends the same request again, so a burst
149
+ that the API spreads over a few seconds never reaches your code as an error. Since 0.1.3.
150
+
151
+ | | |
152
+ |---|---|
153
+ | Retried | An answer of **429 or 503 that carries `Retry-After`**, as seconds (`1`, `1.5`) or an HTTP-date, for any method of the client. |
154
+ | Not retried | Every other status (400, 402, 404, 409, 500 and the rest), a 429 or 503 **without** the header (the API's limit on requests in flight answers a plain `503` like that), a timeout and a network error: after those the client cannot know whether the request arrived. |
155
+ | How often | `max_retries=3` times after the first attempt. `max_retries=0` turns retrying off. |
156
+ | How long | Never less than the header states, plus a random addition of up to twice as much, so the calls of a burst that were refused together come back spread out, and never more than `max_retry_wait`. A stated wait above `max_retry_wait=10.0` seconds is not waited at all: the error is raised at once (the Developer plan's daily cap, `429 fair_use_exceeded`, states the seconds to midnight). |
157
+ | Worst case | One call waits at most `max_retries * max_retry_wait` seconds, 30 by default, on top of its requests. The API states one second today, so each retry waits between one and three seconds: a call refused once adds one to three seconds, a call that uses all three retries adds three to nine. |
158
+ | The request | Identical on every attempt, byte for byte. `record_action` chooses the `action_id` before the first attempt, so every attempt names the same action and the API records it once. |
159
+
160
+ ```python
161
+ from commitlayer import Client, CommitLayerError
162
+
163
+ cl = Client(max_retries=3, max_retry_wait=10.0) # the defaults
164
+ single = Client(max_retries=0) # never retry: the first refusal is raised
165
+
166
+ try:
167
+ cl.record_action("refund_workflow", "order_10231", action_id="refund:order_10231")
168
+ except CommitLayerError as e:
169
+ e.status, e.code # 429, "workspace_busy": the last answer, as before
170
+ e.retry_after # seconds the last answer asked to wait, or None when it stated none
171
+ e.attempts # how many times the request was sent (4 once three retries are used up)
172
+ ```
173
+
174
+ One request is the exception. `POST /v1/actions` is idempotent on `action_id`, and the API may answer `503 busy`
175
+ after the action itself is stored, so a recording that names no `action_id` is sent once and never repeated.
176
+ `record_action` and the `@cl.action` decorator always name one; this only concerns a body you build yourself for
177
+ `cl.request("POST", "/v1/actions", ...)` or an inline `cl.verify(action=...)` that is stored.
178
+
179
+ For the same reason a `503` that `record_action` still raises, after its retries or without any, does not prove
180
+ the action is absent: the API may have stored it and failed only to verify it in time. Recording it again with the
181
+ same `action_id` is safe, and `cl.get_action(action_id)` says whether it is there.
182
+
183
+ Every attempt is a request to the API, and today a write the API refuses as `workspace_busy` or `busy` has already
184
+ been counted against the plan's write requests a minute (60 on the Developer plan). A large burst that is mostly
185
+ refused and retried can therefore spend that minute's budget and end in `429 rate_limited`. Retries make a burst
186
+ succeed, not go faster: a caller that sends its writes a few at a time is seldom refused in the first place.
187
+
188
+ The wait blocks the calling thread (`time.sleep`), the decorator included, and a retried poll can add up to the
189
+ same bound to `wait_for_settlement(timeout=...)`. In an event loop, call the client from a worker thread
190
+ (`await asyncio.to_thread(cl.record_action, ...)`) or pass `max_retries=0` and schedule the retry yourself from
191
+ `e.retry_after`. Each retry writes one line at INFO level to the `commitlayer` logger: method, path, status, code and
192
+ the wait, never the key or the body.
193
+
194
+ A custom `transport` is a function `(method, path, body)` that returns `(status, payload)` or
195
+ `(status, payload, headers)`. Only the second form can be retried: without response headers there is no stated
196
+ wait, so the first refusal is raised as it always was. `headers` is a dict or another mapping, the headers object
197
+ of `urllib` and `http.client` (`response.headers`), or a list of `(name, value)` pairs; the name is matched in any
198
+ case, and a header that is there twice counts at the longer wait.
199
+
200
+ ## Correct a failed action
201
+
202
+ ```python
203
+ cl.record_action(
204
+ "refund_workflow",
205
+ "order_10231",
206
+ params={"amount": 180.0},
207
+ action_id="refund:order_10231:fix",
208
+ compensates="refund:order_10231",
209
+ )
210
+ ```
211
+
212
+ Once the correction settles PASS, the failed action carries `resolution.state == "compensated"`; its own verdict never changes.
@@ -0,0 +1,6 @@
1
+ commitlayer/__init__.py,sha256=tiZDE66t7UzfAnjMwxoGDQLXTUY8X43A2gtlVPL_Xdg,26848
2
+ commitlayer-0.1.3.dist-info/licenses/LICENSE,sha256=0vhmIhIFNhgH1c9Yg3fPGr0tYr606CAcOisVbgKTbb8,1077
3
+ commitlayer-0.1.3.dist-info/METADATA,sha256=nnnVXwSDM2NRIIn47aiscRukin3JUTTYweA1-o7AkH0,11236
4
+ commitlayer-0.1.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ commitlayer-0.1.3.dist-info/top_level.txt,sha256=mzPRxNFVi1RnLNsSqXY4BptrmaWkxr3goPiHYITbzCU,12
6
+ commitlayer-0.1.3.dist-info/RECORD,,
@@ -1,139 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: commitlayer
3
- Version: 0.1.0
4
- Summary: CommitLayer Python SDK: record agent actions, push facts, read verdicts, draft contracts
5
- Author-email: "Asterfold Labs, Inc." <hello@commitlayer.ai>
6
- License-Expression: MIT
7
- Project-URL: Homepage, https://commitlayer.ai
8
- Project-URL: Documentation, https://commitlayer.ai/docs
9
- Project-URL: Changelog, https://commitlayer.ai/changelog
10
- Project-URL: Source, https://github.com/kobikwelu/stateprf-svcs/tree/main/sdk/python
11
- Keywords: ai-agents,verification,audit,mcp,observability
12
- Classifier: Development Status :: 4 - Beta
13
- Classifier: Intended Audience :: Developers
14
- Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.10
16
- Classifier: Programming Language :: Python :: 3.11
17
- Classifier: Programming Language :: Python :: 3.12
18
- Classifier: Programming Language :: Python :: 3.13
19
- Classifier: Topic :: Software Development :: Libraries
20
- Requires-Python: >=3.10
21
- Description-Content-Type: text/markdown
22
- License-File: LICENSE
23
- Dynamic: license-file
24
-
25
- # commitlayer (Python)
26
-
27
- Record agent actions, push facts from systems of record, read verdicts and draft contracts. Standard library
28
- only; Python 3.10+.
29
-
30
- ```bash
31
- pip install ./sdk/python # from this repository
32
- export COMMITLAYER_API_KEY=spk_... # the agent runtime's key: a *recorder* key (records actions, nothing else)
33
- export COMMITLAYER_EVIDENCE_KEY=spk_... # the pipeline's key: an *evidence* key bound to the sources it pushes for
34
- # COMMITLAYER_API_URL defaults to https://api.commitlayer.ai. One credential per side of the line: the key that
35
- # records an action can never also supply the facts that verify it.
36
- ```
37
-
38
- ## Record an action where it happens
39
-
40
- ```python
41
- from commitlayer import Client
42
-
43
- cl = Client(agent_id="support-bot")
44
-
45
-
46
- @cl.action(
47
- "refund_workflow",
48
- subject=lambda order_id, **_: order_id,
49
- params=lambda amount, **_: {"amount": amount},
50
- subject_kind="order",
51
- action_id=lambda order_id, **_: f"refund:{order_id}", # retries update one claim instead of recording two
52
- )
53
- def refund(order_id: str, amount: float) -> dict:
54
- return payments.refund(order_id, amount) # the agent's own work, unchanged
55
-
56
-
57
- refund("order_10231", 180.0)
58
- print(refund.last_recorded["verification"]["summary"]["headline"])
59
- ```
60
-
61
- The action is recorded **before** the function runs, so its request time precedes every effect. The function's
62
- return value is never changed and never consulted: verification reads the systems of record. If the API cannot
63
- be reached the function still runs and a warning is logged (`fail_open=True`); pass `fail_open=False` to raise.
64
-
65
- ## Push facts, with a watermark
66
-
67
- Use an **evidence** key here, bound to the sources it pushes for (Settings → API keys). The key your agent runtime records actions with is a **recorder** key and cannot push facts: the credential that records an action never also supplies the facts that verify it.
68
-
69
- ```python
70
- import os
71
-
72
- evidence = Client(api_key=os.environ["COMMITLAYER_EVIDENCE_KEY"]) # the pipeline's own client, not the runtime's
73
-
74
- evidence.push_facts(
75
- [
76
- {
77
- "source": "crm",
78
- "subject_id": "order_10231",
79
- "fact_type": "note_added",
80
- "occurred_at": "2026-10-13T10:42:09Z",
81
- }
82
- ],
83
- watermarks={"crm": "2026-10-13T10:45:00Z"}, # everything up to here has been sent for crm
84
- )
85
- ```
86
-
87
- A verdict that is not yet a PASS settles only when its window has closed **and** every source it reads has a
88
- watermark past the end of the window. Declare one when your feed lags; a source that never declares one is taken
89
- as current.
90
-
91
- ## Draft a contract from what was recorded
92
-
93
- ```python
94
- d = cl.draft_contract("refund_order", lookback_days=30)
95
- print(d["yaml"]) # expected effects, window, preconditions, limits, from the sample
96
- print(d["stats"]["effects"])
97
- v = cl.validate_contract(d["yaml"]) # errors, and weakening warnings against the version it would replace
98
- cl.save_contract(d["yaml"]) # the response carries the same warnings
99
- ```
100
-
101
- Every value in a draft is what the sample showed, not what the policy says. Review it before saving.
102
-
103
- ## Read a verdict
104
-
105
- ```python
106
- v = cl.get_action("refund:order_10231")
107
- v["status"] # pending | settled
108
- v["settlement"]["waiting_on"] # sources still behind the window, if any
109
- v["reversal"] # the later record that undid the action, if any
110
- v["sources"] # trust level and watermark per source the contract read
111
- ```
112
-
113
- ## Wait for the verdict before saying "done"
114
-
115
- ```python
116
- v = cl.wait_for_settlement("refund:order_10231", timeout=300) # blocks until settled or 5 minutes
117
- if v["timed_out"]:
118
- ... # still pending: your policy, never "success"
119
- elif v["lenses"]["outcome"]["verdict"] == "PASS":
120
- notify_customer("Your order is cancelled and refunded.")
121
- else:
122
- open_recovery(v) # FAIL: the reasons name what is missing or forbidden
123
- ```
124
-
125
- The API holds each call for up to 60 seconds; the SDK loops. The gate reads evidence; it never changes a verdict.
126
-
127
- ## Correct a failed action
128
-
129
- ```python
130
- cl.record_action(
131
- "refund_workflow",
132
- "order_10231",
133
- params={"amount": 180.0},
134
- action_id="refund:order_10231:fix",
135
- compensates="refund:order_10231",
136
- )
137
- ```
138
-
139
- Once the correction settles PASS, the failed action carries `resolution.state == "compensated"`; its own verdict never changes.
@@ -1,6 +0,0 @@
1
- commitlayer/__init__.py,sha256=YDCQRTD6o6figdmxSmMgJFyp-ktx0iZ_u-hGsi9L3XQ,13023
2
- commitlayer-0.1.0.dist-info/licenses/LICENSE,sha256=0vhmIhIFNhgH1c9Yg3fPGr0tYr606CAcOisVbgKTbb8,1077
3
- commitlayer-0.1.0.dist-info/METADATA,sha256=umb4bINVFXjYuEg0iyjTykU69DBX_cWJxZlvS4gAKmM,5333
4
- commitlayer-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
- commitlayer-0.1.0.dist-info/top_level.txt,sha256=mzPRxNFVi1RnLNsSqXY4BptrmaWkxr3goPiHYITbzCU,12
6
- commitlayer-0.1.0.dist-info/RECORD,,