commitlayer 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,306 @@
1
+ """CommitLayer Python SDK: record agent actions, push facts, read verdicts, draft contracts.
2
+
3
+ Standard library only. One client per workspace API key::
4
+
5
+ from commitlayer import Client
6
+
7
+ cl = Client(api_key="spk_...") # COMMITLAYER_API_KEY / COMMITLAYER_API_URL are read when omitted
8
+
9
+ @cl.action("refund_workflow", subject=lambda order_id, **_: order_id, params=lambda amount, **_: {"amount": amount})
10
+ def refund(order_id: str, amount: float) -> dict:
11
+ ... # the agent's own work, unchanged
12
+
13
+ The decorator records the action **before** the function runs, so the request time precedes every effect, and
14
+ never changes what the function returns. Recording failures are logged and swallowed by default
15
+ (``fail_open=True``): a verifier that is unreachable must not stop the business action, and the gap shows up as
16
+ an action that was never recorded rather than one that never happened. Set ``fail_open=False`` to raise.
17
+
18
+ Verification itself is done by the API from the systems of record; nothing here consults the function's result.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import functools
24
+ import json
25
+ import logging
26
+ import os
27
+ import time
28
+ import urllib.error
29
+ import urllib.request
30
+ import uuid
31
+ from collections.abc import Callable
32
+ from datetime import UTC, datetime
33
+ from typing import Any
34
+
35
+ __all__ = ["Client", "CommitLayerError", "__version__"]
36
+ __version__ = "0.1.0"
37
+
38
+ log = logging.getLogger("commitlayer")
39
+
40
+ Transport = Callable[[str, str, dict[str, Any] | None], tuple[int, dict[str, Any]]]
41
+
42
+
43
+ class CommitLayerError(RuntimeError):
44
+ def __init__(self, status: int, code: str, message: str, details: Any = None):
45
+ super().__init__(f"{code} ({status}): {message}")
46
+ self.status, self.code, self.message, self.details = status, code, message, details
47
+
48
+
49
+ def _now() -> str:
50
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
51
+
52
+
53
+ class Client:
54
+ def __init__(
55
+ self,
56
+ api_key: str | None = None,
57
+ api_url: str | None = None,
58
+ *,
59
+ timeout: float = 20.0,
60
+ transport: Transport | None = None,
61
+ agent_id: str | None = None,
62
+ ):
63
+ self.api_key = api_key or os.environ.get("COMMITLAYER_API_KEY") or ""
64
+ self.api_url = (
65
+ api_url or os.environ.get("COMMITLAYER_API_URL") or "https://api.commitlayer.ai"
66
+ ).rstrip("/")
67
+ self.timeout = timeout
68
+ self.agent_id = agent_id
69
+ self._transport = transport or self._http
70
+ if not self.api_key and transport is None:
71
+ raise ValueError("api_key is required (or set COMMITLAYER_API_KEY)")
72
+
73
+ # ---------------- transport ----------------
74
+
75
+ def _http(self, method: str, path: str, body: dict[str, Any] | None) -> tuple[int, dict[str, Any]]:
76
+ data = json.dumps(body).encode() if body is not None else None
77
+ req = urllib.request.Request(
78
+ self.api_url + path,
79
+ data=data,
80
+ method=method,
81
+ headers={
82
+ "X-API-Key": self.api_key,
83
+ "Content-Type": "application/json",
84
+ "Accept": "application/json",
85
+ "User-Agent": f"commitlayer-python/{__version__}",
86
+ },
87
+ )
88
+ try:
89
+ with urllib.request.urlopen(req, timeout=self.timeout) as r: # noqa: S310 - fixed https host
90
+ raw = r.read()
91
+ return r.status, (json.loads(raw) if raw else {})
92
+ except urllib.error.HTTPError as e:
93
+ raw = e.read()
94
+ try:
95
+ return e.code, json.loads(raw) if raw else {}
96
+ except ValueError:
97
+ return e.code, {
98
+ "error": {"code": "http_error", "message": raw.decode(errors="replace")[:300]}
99
+ }
100
+
101
+ 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:
104
+ err = payload.get("error") if isinstance(payload, dict) else None
105
+ if isinstance(err, dict):
106
+ raise CommitLayerError(
107
+ status, err.get("code", "error"), err.get("message", ""), err.get("details")
108
+ )
109
+ raise CommitLayerError(status, "error", str(payload)[:300])
110
+ return payload
111
+
112
+ # ---------------- actions and facts ----------------
113
+
114
+ def record_action(
115
+ self,
116
+ contract_id: str,
117
+ subject_id: str,
118
+ *,
119
+ params: dict[str, Any] | None = None,
120
+ action_id: str | None = None,
121
+ action_type: str | None = None,
122
+ subject_kind: str | None = None,
123
+ workflow_id: str | None = None,
124
+ agent_id: str | None = None,
125
+ requested_at: str | None = None,
126
+ channel: str | None = None,
127
+ compensates: str | None = None,
128
+ contract_version: int | None = None,
129
+ ) -> dict[str, Any]:
130
+ """``POST /v1/actions``: record one action. ``compensates`` names an earlier action this one corrects;
131
+ once this one settles PASS, that action is marked compensated (its own verdict never changes). Returns ``{action, verification, allowance}``. The verification
132
+ is provisional until its settlement window closes and every source it reads has caught up."""
133
+ body = {
134
+ "action_id": action_id or f"act_{uuid.uuid4().hex}",
135
+ "contract_id": contract_id,
136
+ "subject_id": str(subject_id),
137
+ "params": params or {},
138
+ "requested_at": requested_at or _now(),
139
+ }
140
+ for k, v in (
141
+ ("action_type", action_type),
142
+ ("subject_kind", subject_kind),
143
+ ("workflow_id", workflow_id),
144
+ ("agent_id", agent_id or self.agent_id),
145
+ ("channel", channel),
146
+ ("compensates", compensates),
147
+ ("contract_version", contract_version),
148
+ ):
149
+ if v is not None:
150
+ body[k] = v
151
+ return self._call("POST", "/v1/actions", body)
152
+
153
+ def push_facts(
154
+ self,
155
+ facts: list[dict[str, Any]],
156
+ *,
157
+ links: list[dict[str, Any]] | None = None,
158
+ watermarks: dict[str, str] | None = None,
159
+ ) -> dict[str, Any]:
160
+ """``POST /v1/facts``. ``watermarks`` (source → time) states that everything up to that time has been sent
161
+ for the source; settlement waits on it instead of the clock."""
162
+ body: dict[str, Any] = {"facts": facts}
163
+ if links:
164
+ body["links"] = links
165
+ if watermarks:
166
+ body["watermarks"] = watermarks
167
+ return self._call("POST", "/v1/facts", body)
168
+
169
+ def verify(
170
+ self,
171
+ action_id: str | None = None,
172
+ *,
173
+ action: dict[str, Any] | None = None,
174
+ facts: list[dict[str, Any]] | None = None,
175
+ links: list[dict[str, Any]] | None = None,
176
+ dry_run: bool = False,
177
+ ) -> dict[str, Any]:
178
+ """``POST /v1/actions/verify``: verify now, by id or inline. ``dry_run`` stores nothing."""
179
+ body: dict[str, Any] = {"dry_run": dry_run}
180
+ if action_id:
181
+ body["action_id"] = action_id
182
+ if action:
183
+ body["action"] = action
184
+ if facts:
185
+ body["facts"] = facts
186
+ if links:
187
+ body["links"] = links
188
+ return self._call("POST", "/v1/actions/verify", body)
189
+
190
+ def get_action(self, action_ref: str) -> dict[str, Any]:
191
+ return self._call("GET", f"/v1/actions/{action_ref}")
192
+
193
+ def wait_for_settlement(self, action_ref: str, *, timeout: float = 300.0) -> dict[str, Any]:
194
+ """The completion gate: block until the action's verdict settles or ``timeout`` seconds pass, and return
195
+ the verification (``status`` is ``settled`` or, on timeout, ``pending``; ``timed_out`` says which). The
196
+ 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."""
198
+ deadline = time.monotonic() + max(0.0, timeout)
199
+ while True:
200
+ budget = max(0.0, min(60.0, deadline - time.monotonic()))
201
+ v = self._call("GET", f"/v1/actions/{action_ref}/wait?timeout={budget:.0f}")
202
+ if not v.get("timed_out") or budget < 1 or time.monotonic() >= deadline:
203
+ return v
204
+
205
+ 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."""
207
+ return self._call(method, path, body)
208
+
209
+ # ---------------- contracts ----------------
210
+
211
+ def draft_contract(
212
+ self,
213
+ action_type: str | None = None,
214
+ *,
215
+ contract_id: str | None = None,
216
+ lookback_days: int = 30,
217
+ lookahead: str = "24h",
218
+ min_share: float = 0.8,
219
+ ) -> dict[str, Any]:
220
+ """``POST /v1/contracts/draft``: a contract drafted from recorded actions and the facts around them.
221
+ Returns ``{yaml, contract, errors, warnings, stats}``; nothing is saved."""
222
+ return self._call(
223
+ "POST",
224
+ "/v1/contracts/draft",
225
+ {
226
+ "action_type": action_type,
227
+ "contract_id": contract_id,
228
+ "lookback_days": lookback_days,
229
+ "lookahead": lookahead,
230
+ "min_share": min_share,
231
+ },
232
+ )
233
+
234
+ def validate_contract(self, yaml_text: str) -> dict[str, Any]:
235
+ """``POST /v1/contracts/validate``: errors, compiled lenses and weakening warnings against the version
236
+ it would replace."""
237
+ return self._call("POST", "/v1/contracts/validate", {"yaml": yaml_text})
238
+
239
+ def save_contract(self, yaml_text: str) -> dict[str, Any]:
240
+ """``POST /v1/contracts``: save a version. The response carries ``warnings`` when it is weaker than the
241
+ last one."""
242
+ return self._call("POST", "/v1/contracts", {"yaml": yaml_text})
243
+
244
+ # ---------------- decorator ----------------
245
+
246
+ def action(
247
+ self,
248
+ contract_id: str,
249
+ *,
250
+ subject: Callable[..., Any] | str,
251
+ params: Callable[..., dict[str, Any]] | None = None,
252
+ action_type: str | None = None,
253
+ subject_kind: str | None = None,
254
+ workflow_id: Callable[..., str | None] | str | None = None,
255
+ agent_id: str | None = None,
256
+ action_id: Callable[..., str] | None = None,
257
+ compensates: Callable[..., str | None] | str | None = None,
258
+ fail_open: bool = True,
259
+ on_recorded: Callable[[dict[str, Any]], None] | None = None,
260
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
261
+ """Record the decorated call as an action under ``contract_id`` before it runs.
262
+
263
+ ``subject`` is the keyword argument name holding the subject id, or a callable over the bound arguments
264
+ returning it. ``params`` is a callable over the bound arguments returning the parameters the contract
265
+ limits (an amount, a tier). ``action_id`` makes retries idempotent: give it the same id and the API
266
+ updates the one claim rather than recording two. The verification returned by the API is passed to
267
+ ``on_recorded`` and stored on the function as ``last_recorded``.
268
+ """
269
+ import inspect
270
+
271
+ def deco(fn: Callable[..., Any]) -> Callable[..., Any]:
272
+ sig = inspect.signature(fn)
273
+
274
+ @functools.wraps(fn)
275
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
276
+ try:
277
+ bound = sig.bind_partial(*args, **kwargs)
278
+ bound.apply_defaults()
279
+ ba = dict(bound.arguments)
280
+ subj = ba[subject] if isinstance(subject, str) else subject(**ba)
281
+ wf = workflow_id(**ba) if callable(workflow_id) else workflow_id
282
+ rec = self.record_action(
283
+ contract_id,
284
+ str(subj),
285
+ params=params(**ba) if params else {},
286
+ action_id=action_id(**ba) if action_id else None,
287
+ action_type=action_type,
288
+ subject_kind=subject_kind,
289
+ workflow_id=wf,
290
+ agent_id=agent_id,
291
+ compensates=compensates(**ba) if callable(compensates) else compensates,
292
+ )
293
+ wrapper.last_recorded = rec # type: ignore[attr-defined]
294
+ if on_recorded:
295
+ on_recorded(rec)
296
+ except Exception as e: # noqa: BLE001 - the business action must not depend on the verifier
297
+ wrapper.last_recorded = None # type: ignore[attr-defined]
298
+ if not fail_open:
299
+ raise
300
+ log.warning("commitlayer: action not recorded for %s: %s", fn.__name__, e)
301
+ return fn(*args, **kwargs)
302
+
303
+ wrapper.last_recorded = None # type: ignore[attr-defined]
304
+ return wrapper
305
+
306
+ return deco
@@ -0,0 +1,139 @@
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.
@@ -0,0 +1,6 @@
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,,
@@ -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 Asterfold Labs, Inc.
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
+ commitlayer