primarypath-sdk 1.0.0rc1__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,715 @@
1
+ """Primary Path client SDK.
2
+
3
+ The framework-agnostic side of the product: POST the approval request, then
4
+ poll for the decision (or receive it on your callback_url). The pause is
5
+ durable on both sides — the service holds the request in its log, and the
6
+ caller can crash and re-wait on the same approval_id.
7
+
8
+ The sync client is stdlib-only. The async client needs httpx
9
+ (pip install primarypath-sdk[async]).
10
+
11
+ Resilience, because an agent may pause for hours or days: every call
12
+ retries transient failures (connection errors, 429, 502/503/504) with
13
+ exponential backoff and full jitter, honouring Retry-After; the policy
14
+ is `RetryPolicy` on the client. `wait_for_decision` keeps polling
15
+ through outages until its own timeout, backs its poll interval off to
16
+ `max_interval`, and stops on a `cancel` event.
17
+
18
+ Retries are safe for every write because each non-idempotent call
19
+ (annotate, incident, ingest, decide, cancel, request-changes, redeem)
20
+ generates an `Idempotency-Key` once and sends the SAME key on every
21
+ attempt: the server records the key with the events, so a retry after
22
+ a lost response returns the original result and writes nothing — one
23
+ annotation, one incident, one redeemed grant that this caller may
24
+ dispatch on. Pass `idempotency_key=` to control the key yourself (for
25
+ example, derive it from your own step id so a crashed-and-restarted
26
+ agent replays too). Approval creation is idempotent by its own id.
27
+
28
+ Identifiers are percent-encoded into paths; the server accepts only
29
+ URL-safe ids (letters, digits, . _ - ~ @ + =, and : in run_id), so every
30
+ approval that can be created can be addressed.
31
+
32
+ Execution grants (the approve->execute seam): a granted approval carries
33
+ `grant`, an Ed25519-signed, short-lived, single-use capability bound to
34
+ the approval's action digest. The EXECUTOR — whatever holds the tool
35
+ credentials — calls `verify_grant(...)` offline against the pinned
36
+ public-key ring (`client.signing_keys()`), then `client.redeem_grant(...)`
37
+ right before dispatch: the server accepts each grant exactly once and
38
+ appends `grant_redeemed` to the chain. `verify_grant` needs
39
+ `cryptography` (pip install primarypath-sdk[grants]).
40
+ """
41
+ from __future__ import annotations
42
+
43
+ import base64
44
+ import email.utils
45
+ import hashlib
46
+ import json
47
+ import random
48
+ import threading
49
+ import time
50
+ import urllib.error
51
+ import urllib.parse
52
+ import urllib.request
53
+ import uuid
54
+ from dataclasses import dataclass, field
55
+
56
+ __all__ = ["PrimaryPathClient", "AsyncPrimaryPathClient", "ApiError",
57
+ "TransportError", "DecisionTimeout", "WaitCancelled", "RetryPolicy",
58
+ "GrantInvalid", "NotCanonicalizable", "action_digest", "jcs",
59
+ "verify_grant", "GRANT_SIGNED_FIELDS"]
60
+
61
+
62
+ # -- RFC 8785 JSON Canonicalization Scheme (a copy of the server's app/jcs.py;
63
+ # the server's tests assert the two agree). JSON.stringify over an
64
+ # object with keys sorted by UTF-16 code units is the reference; this
65
+ # reproduces it byte for byte, ECMAScript number formatting included,
66
+ # so a digest computed here equals one computed in TypeScript or by
67
+ # the server. --------------------------------------------------------------
68
+
69
+ import math
70
+
71
+ # ECMAScript Number::toString thresholds
72
+ _EXP_UPPER = 21 # >= 1e21 switches to exponent form
73
+ _EXP_LOWER = -6 # < 1e-6 switches to exponent form
74
+ _MAX_SAFE = 2 ** 53
75
+ _SHORT = {8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r"}
76
+
77
+
78
+ class NotCanonicalizable(ValueError):
79
+ """A value JSON (and therefore JCS) cannot represent."""
80
+
81
+
82
+ def _es_number(x: float) -> str:
83
+ """Number::toString for a finite double: the shortest round-trip digit
84
+ string (Python's repr yields the same digits as ECMAScript's
85
+ "shortest" rule) laid out with ECMAScript's rules."""
86
+ if x == 0:
87
+ return "0" # -0 prints as "0"
88
+ sign = "-" if x < 0 else ""
89
+ r = repr(abs(x)) # '1.5', '1e-07', '1.2345e+21', '123.0'
90
+ mantissa, _, exp = r.partition("e")
91
+ e = int(exp) if exp else 0
92
+ int_part, _, frac_part = mantissa.partition(".")
93
+ int_digits = int_part.lstrip("0")
94
+ if int_digits:
95
+ n = len(int_digits) + e
96
+ else:
97
+ n = e - (len(frac_part) - len(frac_part.lstrip("0")))
98
+ digits = (int_digits + frac_part if int_digits else frac_part.lstrip("0"))
99
+ digits = digits.rstrip("0")
100
+ k = len(digits)
101
+ if k == 0:
102
+ return "0"
103
+ if k <= n <= _EXP_UPPER:
104
+ return sign + digits + "0" * (n - k)
105
+ if 0 < n <= _EXP_UPPER:
106
+ return sign + digits[:n] + "." + digits[n:]
107
+ if _EXP_LOWER < n <= 0:
108
+ return sign + "0." + "0" * (-n) + digits
109
+ exp10 = n - 1
110
+ exp_s = ("+" if exp10 >= 0 else "-") + str(abs(exp10))
111
+ if k == 1:
112
+ return sign + digits + "e" + exp_s
113
+ return sign + digits[0] + "." + digits[1:] + "e" + exp_s
114
+
115
+
116
+ def _string(s: str) -> str:
117
+ """JSON.stringify's string form: only `"`, backslash and control
118
+ characters are escaped (short forms for \\b \\f \\n \\r \\t, else
119
+ \\u00xx lowercase); everything else, non-ASCII included, is emitted
120
+ as is."""
121
+ out = ['"']
122
+ for ch in s:
123
+ o = ord(ch)
124
+ if ch == '"':
125
+ out.append('\\"')
126
+ elif ch == "\\":
127
+ out.append("\\\\")
128
+ elif o < 0x20:
129
+ out.append(_SHORT.get(o, f"\\u{o:04x}"))
130
+ elif 0xD800 <= o <= 0xDFFF:
131
+ raise NotCanonicalizable("lone surrogate in string")
132
+ else:
133
+ out.append(ch)
134
+ out.append('"')
135
+ return "".join(out)
136
+
137
+
138
+ def jcs(value) -> str:
139
+ """Serialize `value` per RFC 8785."""
140
+ if value is None:
141
+ return "null"
142
+ if value is True:
143
+ return "true"
144
+ if value is False:
145
+ return "false"
146
+ if isinstance(value, int):
147
+ # JCS numbers are IEEE doubles: an integer beyond 2^53 is what a
148
+ # JSON parser in any language rounds it to
149
+ if abs(value) > _MAX_SAFE:
150
+ return _es_number(float(value))
151
+ return str(value)
152
+ if isinstance(value, float):
153
+ if math.isnan(value) or math.isinf(value):
154
+ raise NotCanonicalizable("NaN and Infinity are not JSON")
155
+ return _es_number(value)
156
+ if isinstance(value, str):
157
+ return _string(value)
158
+ if isinstance(value, (list, tuple)):
159
+ return "[" + ",".join(jcs(v) for v in value) + "]"
160
+ if isinstance(value, dict):
161
+ items = []
162
+ for k in sorted(value, key=lambda k: str(k).encode("utf-16-be")):
163
+ if not isinstance(k, str):
164
+ raise NotCanonicalizable(f"object key is not a string: {k!r}")
165
+ items.append(_string(k) + ":" + jcs(value[k]))
166
+ return "{" + ",".join(items) + "}"
167
+ raise NotCanonicalizable(f"not a JSON value: {type(value).__name__}")
168
+
169
+
170
+ def action_digest(tool: str, arguments: dict | None = None,
171
+ reasoning: str | None = None, framework: str | None = None,
172
+ callback_url: str | None = None) -> str:
173
+ """sha256 over the RFC 8785 form of the action — byte-identical to the
174
+ server's `action_digest` (digest_alg "jcs") stamped into
175
+ `approval_requested`, and to the TypeScript SDK's `actionDigest`. An
176
+ executor recomputes it from the exact arguments it is about to
177
+ dispatch."""
178
+ return hashlib.sha256(jcs({
179
+ "tool": tool, "arguments": arguments or {}, "reasoning": reasoning,
180
+ "framework": framework, "callback_url": callback_url,
181
+ }).encode("utf-8")).hexdigest()
182
+
183
+
184
+ GRANT_SIGNED_FIELDS = ("v", "approval_id", "tenant", "agent_id", "tool",
185
+ "action_digest", "issued_ms", "expires_ms", "nonce")
186
+
187
+
188
+ class GrantInvalid(Exception):
189
+ """An execution grant that must not be honored, and why."""
190
+
191
+
192
+ def verify_grant(grant: dict, keys: dict[str, str], *,
193
+ tool: str | None = None, arguments: dict | None = None,
194
+ reasoning: str | None = None, framework: str | None = None,
195
+ callback_url: str | None = None,
196
+ expected_digest: str | None = None,
197
+ approval_id: str | None = None,
198
+ now_ms: int | None = None) -> dict:
199
+ """Verify an execution grant OFFLINE and return it.
200
+
201
+ `keys` is the public-key ring (`key_id` -> base64 raw Ed25519 public
202
+ key) from `/api/audit/keys` — pin it out of band for authenticity.
203
+ Pass the action the executor is about to run (`tool` + `arguments`
204
+ and, if it knows them, `reasoning`/`framework`/`callback_url`) so the
205
+ digest is recomputed and compared; or `expected_digest` when only the
206
+ digest is known. Raises GrantInvalid on any failure. Single use is
207
+ enforced ONLINE by `redeem_grant`, not here."""
208
+ try:
209
+ from cryptography.exceptions import InvalidSignature
210
+ from cryptography.hazmat.primitives.asymmetric import ed25519
211
+ except ImportError: # pragma: no cover - packaging
212
+ raise GrantInvalid("verify_grant needs `cryptography` "
213
+ "(pip install primarypath-sdk[grants])") from None
214
+ if not isinstance(grant, dict) or grant.get("v") != 1:
215
+ raise GrantInvalid("unsupported grant version")
216
+ missing = [k for k in GRANT_SIGNED_FIELDS + ("key_id", "signature")
217
+ if k not in grant]
218
+ if missing:
219
+ raise GrantInvalid(f"grant is missing {', '.join(missing)}")
220
+ pub = keys.get(grant["key_id"])
221
+ if pub is None:
222
+ raise GrantInvalid(f"unknown signing key {grant['key_id']}: not in "
223
+ f"the pinned ring")
224
+ message = jcs({k: grant[k] for k in GRANT_SIGNED_FIELDS})
225
+ try:
226
+ ed25519.Ed25519PublicKey.from_public_bytes(
227
+ base64.b64decode(pub)).verify(
228
+ base64.b64decode(grant["signature"]), message.encode("utf-8"))
229
+ except (InvalidSignature, ValueError):
230
+ raise GrantInvalid("signature does not verify") from None
231
+ now = int(time.time() * 1000) if now_ms is None else now_ms
232
+ if now > int(grant["expires_ms"]):
233
+ raise GrantInvalid(f"grant expired at {grant['expires_ms']}")
234
+ if approval_id is not None and grant["approval_id"] != approval_id:
235
+ raise GrantInvalid("grant is for a different approval")
236
+ if tool is not None and grant["tool"] != tool:
237
+ raise GrantInvalid(f"grant is for tool {grant['tool']}, not {tool}")
238
+ if tool is not None and expected_digest is None:
239
+ expected_digest = action_digest(tool, arguments, reasoning,
240
+ framework, callback_url)
241
+ if expected_digest is not None and grant["action_digest"] != expected_digest:
242
+ raise GrantInvalid("grant binds a different action than the one "
243
+ "about to execute (digest mismatch)")
244
+ return grant
245
+
246
+
247
+ class DecisionTimeout(TimeoutError):
248
+ pass
249
+
250
+
251
+ class WaitCancelled(Exception):
252
+ """wait_for_decision stopped because its cancel event was set."""
253
+
254
+
255
+ class ApiError(Exception):
256
+ """A non-2xx answer from the service. Raised, never returned: an agent
257
+ that mistakes {"detail": "..."} for an approval will poll a decision
258
+ that can never come."""
259
+
260
+ def __init__(self, status: int, body: object, retry_after: float | None = None):
261
+ detail = body.get("detail") if isinstance(body, dict) else None
262
+ super().__init__(f"primarypath API error {status}"
263
+ + (f": {detail}" if detail else ""))
264
+ self.status = status
265
+ self.body = body
266
+ self.retry_after = retry_after
267
+
268
+
269
+ class TransportError(Exception):
270
+ """The service could not be reached (connection refused, reset, DNS,
271
+ timeout) and the retry policy is exhausted."""
272
+
273
+ def __init__(self, message: str, attempts: int):
274
+ super().__init__(f"{message} (after {attempts} attempt(s))")
275
+ self.attempts = attempts
276
+
277
+
278
+ TRANSIENT_STATUSES = frozenset({429, 502, 503, 504})
279
+
280
+
281
+ @dataclass
282
+ class RetryPolicy:
283
+ """Bounded retries with exponential backoff and full jitter. `attempts`
284
+ counts the first try; delays are min(max_delay, base * 2**n) times a
285
+ random factor in [0, 1] (full jitter), or the server's Retry-After
286
+ when it sends one (capped at retry_after_max)."""
287
+ attempts: int = 5
288
+ base: float = 0.5
289
+ max_delay: float = 30.0
290
+ jitter: bool = True
291
+ retry_after_max: float = 120.0
292
+ statuses: frozenset = field(default_factory=lambda: TRANSIENT_STATUSES)
293
+
294
+ def delay(self, attempt: int, retry_after: float | None = None) -> float:
295
+ if retry_after is not None:
296
+ return max(0.0, min(retry_after, self.retry_after_max))
297
+ d = min(self.max_delay, self.base * (2 ** attempt))
298
+ return random.uniform(0, d) if self.jitter else d
299
+
300
+
301
+ def _p(segment) -> str:
302
+ """A path segment: percent-encode everything but unreserved characters,
303
+ so an id like `run:7@eu` reaches the server as sent."""
304
+ return urllib.parse.quote(str(segment), safe="")
305
+
306
+
307
+ def _key(given: str | None) -> str:
308
+ """The Idempotency-Key for one logical write: the caller's, or a fresh
309
+ random one — generated ONCE per call, then repeated on every retry."""
310
+ return given if given is not None else uuid.uuid4().hex
311
+
312
+
313
+ def _retry_after(value: str | None) -> float | None:
314
+ if not value:
315
+ return None
316
+ value = value.strip()
317
+ if value.isdigit():
318
+ return float(value)
319
+ try:
320
+ when = email.utils.parsedate_to_datetime(value)
321
+ except (TypeError, ValueError):
322
+ return None
323
+ return max(0.0, when.timestamp() - time.time())
324
+
325
+
326
+ def _body_or_raise(status: int, raw: bytes,
327
+ retry_after: float | None = None) -> dict | list:
328
+ try:
329
+ body = json.loads(raw.decode("utf-8")) if raw else None
330
+ except ValueError:
331
+ body = raw.decode("utf-8", "replace")
332
+ if status >= 400:
333
+ raise ApiError(status, body, retry_after)
334
+ return body
335
+
336
+
337
+ def _is_transient(exc: Exception, policy: RetryPolicy) -> bool:
338
+ if isinstance(exc, ApiError):
339
+ return exc.status in policy.statuses
340
+ return isinstance(exc, TransportError)
341
+
342
+
343
+ class PrimaryPathClient:
344
+ def __init__(self, base_url: str = "http://127.0.0.1:8123",
345
+ token: str | None = None, timeout: float = 30.0,
346
+ retry: RetryPolicy | None = None):
347
+ self.base_url = base_url.rstrip("/")
348
+ self.token = token
349
+ self.timeout = timeout
350
+ self.retry = retry or RetryPolicy()
351
+
352
+ def _once(self, method: str, path: str, body: dict | None,
353
+ idem: str | None = None) -> dict | list:
354
+ data = json.dumps(body).encode("utf-8") if body is not None else None
355
+ headers = {"Content-Type": "application/json"}
356
+ if self.token:
357
+ headers["Authorization"] = f"Bearer {self.token}"
358
+ if idem is not None:
359
+ headers["Idempotency-Key"] = idem
360
+ req = urllib.request.Request(f"{self.base_url}{path}", data=data,
361
+ method=method, headers=headers)
362
+ try:
363
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
364
+ return _body_or_raise(resp.status, resp.read())
365
+ except urllib.error.HTTPError as e:
366
+ return _body_or_raise(e.code, e.read(),
367
+ _retry_after(e.headers.get("Retry-After")))
368
+ except (urllib.error.URLError, ConnectionError, TimeoutError) as e:
369
+ raise TransportError(str(getattr(e, "reason", e)), 1) from None
370
+
371
+ def _call(self, method: str, path: str, body: dict | None = None,
372
+ retry: bool = True, idem: str | None = None) -> dict | list:
373
+ """One request under the retry policy; `idem` is the
374
+ Idempotency-Key repeated on every attempt of a write."""
375
+ attempts = self.retry.attempts if retry else 1
376
+ for attempt in range(attempts):
377
+ try:
378
+ return self._once(method, path, body, idem)
379
+ except (ApiError, TransportError) as e:
380
+ if attempt + 1 >= attempts or not _is_transient(e, self.retry):
381
+ if isinstance(e, TransportError):
382
+ raise TransportError(str(e).rsplit(" (after", 1)[0],
383
+ attempt + 1) from None
384
+ raise
385
+ time.sleep(self.retry.delay(attempt, getattr(e, "retry_after", None)))
386
+ raise AssertionError("unreachable")
387
+
388
+ def request_approval(self, run_id: str, call_id: str, tool: str,
389
+ arguments: dict | None = None,
390
+ reasoning: str | None = None,
391
+ framework: str | None = None,
392
+ deadline_ms: int | None = None,
393
+ callback_url: str | None = None,
394
+ supersedes: str | None = None) -> str:
395
+ body = {"run_id": run_id, "call_id": call_id, "tool": tool,
396
+ "arguments": arguments or {}, "reasoning": reasoning}
397
+ if framework is not None:
398
+ body["framework"] = framework
399
+ if supersedes is not None:
400
+ body["supersedes"] = supersedes
401
+ if deadline_ms is not None:
402
+ body["deadline_ms"] = deadline_ms
403
+ if callback_url is not None:
404
+ body["callback_url"] = callback_url
405
+ out = self._call("POST", "/api/approvals", body)
406
+ return out["approval_id"]
407
+
408
+ def get(self, approval_id: str) -> dict:
409
+ return self._call("GET", f"/api/approvals/{_p(approval_id)}")
410
+
411
+ def list(self, status: str | None = None, limit: int = 100,
412
+ cursor: int = 0) -> list:
413
+ q = f"?limit={limit}&cursor={cursor}"
414
+ if status:
415
+ q += f"&status={_p(status)}"
416
+ return self._call("GET", f"/api/approvals{q}")
417
+
418
+ def wait_for_decision(self, approval_id: str, interval: float = 1.0,
419
+ timeout: float | None = None,
420
+ cancel: threading.Event | None = None,
421
+ max_interval: float | None = None) -> dict:
422
+ """Poll until the approval leaves `pending` (any terminal status).
423
+
424
+ Built for long pauses: transient failures (outage, 429, 5xx) are
425
+ tolerated and polling continues until `timeout`; the poll interval
426
+ backs off from `interval` toward `max_interval` (default: no
427
+ backoff) with jitter; `cancel` (a threading.Event) stops the wait
428
+ with WaitCancelled. `timeout` is the only way it gives up on its
429
+ own."""
430
+ start = time.monotonic()
431
+ current = interval
432
+ ceiling = max_interval if max_interval is not None else interval
433
+ while True:
434
+ if cancel is not None and cancel.is_set():
435
+ raise WaitCancelled(approval_id)
436
+ try:
437
+ a = self.get(approval_id)
438
+ if a.get("status") != "pending": # any terminal status
439
+ return a
440
+ except (ApiError, TransportError) as e:
441
+ if not _is_transient(e, self.retry):
442
+ raise
443
+ if timeout is not None and time.monotonic() - start > timeout:
444
+ raise DecisionTimeout(f"no decision on {approval_id} in {timeout}s")
445
+ pause = random.uniform(current * 0.8, current * 1.2)
446
+ if cancel is not None:
447
+ if cancel.wait(pause):
448
+ raise WaitCancelled(approval_id)
449
+ else:
450
+ time.sleep(pause)
451
+ current = min(ceiling, current * 1.5)
452
+
453
+ def decide(self, approval_id: str, approved: bool, reviewer: str,
454
+ reason: str = "", idempotency_key: str | None = None) -> dict:
455
+ return self._call("POST", f"/api/approvals/{_p(approval_id)}/decision",
456
+ {"approved": approved, "reviewer": reviewer,
457
+ "reason": reason}, idem=_key(idempotency_key))
458
+
459
+ def annotate(self, approval_id: str, reviewer: str, note: str,
460
+ idempotency_key: str | None = None) -> dict:
461
+ return self._call("POST", f"/api/approvals/{_p(approval_id)}/annotate",
462
+ {"reviewer": reviewer, "note": note},
463
+ idem=_key(idempotency_key))
464
+
465
+ def cancel(self, approval_id: str, reason: str = "",
466
+ idempotency_key: str | None = None) -> dict:
467
+ """Withdraw a pending proposal (agent plane)."""
468
+ return self._call("POST", f"/api/approvals/{_p(approval_id)}/cancel",
469
+ {"reason": reason}, idem=_key(idempotency_key))
470
+
471
+ def request_changes(self, approval_id: str, reviewer: str,
472
+ reason: str, idempotency_key: str | None = None) -> dict:
473
+ """Send a proposal back for changes (human plane)."""
474
+ return self._call("POST",
475
+ f"/api/approvals/{_p(approval_id)}/request-changes",
476
+ {"reviewer": reviewer, "reason": reason},
477
+ idem=_key(idempotency_key))
478
+
479
+ def report_incident(self, approval_id: str, reviewer: str, summary: str,
480
+ severity: str = "sev3",
481
+ idempotency_key: str | None = None) -> dict:
482
+ """A structured outcome event: the executed action caused an
483
+ incident. Counted by the rollout track record."""
484
+ return self._call("POST", f"/api/approvals/{_p(approval_id)}/incident",
485
+ {"reviewer": reviewer, "summary": summary,
486
+ "severity": severity}, idem=_key(idempotency_key))
487
+
488
+ def redeem_grant(self, approval_id: str, nonce: str,
489
+ instance: str | None = None,
490
+ idempotency_key: str | None = None) -> dict:
491
+ """Redeem the approval's execution grant — exactly once, right
492
+ before dispatch (agent plane). 409 (ApiError) if it was already
493
+ redeemed, expired, or does not match. Retried under the same
494
+ Idempotency-Key: if the response is lost, the retry returns the
495
+ result of THIS call's redemption (the grant was spent by us, so
496
+ dispatching is right), while a genuinely second redemption is
497
+ still a 409. The chain's `executor` is the presenting credential,
498
+ written by the server; `instance` is this executor's own name for
499
+ itself ("mcp-gateway@edge-1"), recorded separately as
500
+ self-asserted context."""
501
+ body = {"nonce": nonce}
502
+ if instance is not None:
503
+ body["instance"] = instance
504
+ return self._call("POST", f"/api/approvals/{_p(approval_id)}/redeem",
505
+ body, idem=_key(idempotency_key))
506
+
507
+ def signing_keys(self) -> dict[str, str]:
508
+ """The public-key ring (key_id -> base64 raw Ed25519 public key)
509
+ grants and exports are signed with. Pin it out of band."""
510
+ return self._call("GET", "/api/audit/keys")["keys"]
511
+
512
+ def ingest_run_events(self, run_id: str, events: list[dict],
513
+ idempotency_key: str | None = None) -> int:
514
+ out = self._call("POST", f"/api/runs/{_p(run_id)}/events",
515
+ {"events": events}, idem=_key(idempotency_key))
516
+ return out.get("ingested", 0)
517
+
518
+ def run_audit(self, run_id: str) -> list:
519
+ return self._call("GET", f"/api/runs/{_p(run_id)}/audit")
520
+
521
+ def export_audit(self) -> dict:
522
+ """The whole log: {"chains": [...]}, each chain independently
523
+ verifiable (F24)."""
524
+ return self._call("GET", "/api/audit/export")
525
+
526
+ def export_agent_audit(self, agent: str) -> dict:
527
+ """One agent's chain, signed under its own evidence profile (F24)."""
528
+ return self._call("GET", f"/api/audit/export?agent={_p(agent)}")
529
+
530
+
531
+ class AsyncPrimaryPathClient:
532
+ """Async twin of PrimaryPathClient (agents are async). Requires httpx.
533
+ Same retry policy and long-wait semantics; cancellation is the
534
+ natural asyncio task cancellation, or an asyncio.Event passed as
535
+ `cancel` to wait_for_decision."""
536
+
537
+ def __init__(self, base_url: str = "http://127.0.0.1:8123",
538
+ token: str | None = None, timeout: float = 30.0,
539
+ retry: RetryPolicy | None = None):
540
+ import httpx # local import: optional dependency
541
+
542
+ headers = {"Content-Type": "application/json"}
543
+ if token:
544
+ headers["Authorization"] = f"Bearer {token}"
545
+ self.retry = retry or RetryPolicy()
546
+ self._client = httpx.AsyncClient(base_url=base_url.rstrip("/"),
547
+ headers=headers, timeout=timeout)
548
+
549
+ async def aclose(self) -> None:
550
+ await self._client.aclose()
551
+
552
+ async def __aenter__(self) -> AsyncPrimaryPathClient:
553
+ return self
554
+
555
+ async def __aexit__(self, *exc) -> None:
556
+ await self.aclose()
557
+
558
+ async def _once(self, method: str, path: str, body: dict | None,
559
+ idem: str | None = None) -> dict | list:
560
+ import httpx
561
+
562
+ headers = {"Idempotency-Key": idem} if idem is not None else None
563
+ try:
564
+ r = await self._client.request(method, path, json=body,
565
+ headers=headers)
566
+ except httpx.TransportError as e:
567
+ raise TransportError(str(e) or e.__class__.__name__, 1) from None
568
+ return _body_or_raise(r.status_code, r.content,
569
+ _retry_after(r.headers.get("Retry-After")))
570
+
571
+ async def _call(self, method: str, path: str, body: dict | None = None,
572
+ retry: bool = True, idem: str | None = None) -> dict | list:
573
+ import asyncio
574
+
575
+ attempts = self.retry.attempts if retry else 1
576
+ for attempt in range(attempts):
577
+ try:
578
+ return await self._once(method, path, body, idem)
579
+ except (ApiError, TransportError) as e:
580
+ if attempt + 1 >= attempts or not _is_transient(e, self.retry):
581
+ if isinstance(e, TransportError):
582
+ raise TransportError(str(e).rsplit(" (after", 1)[0],
583
+ attempt + 1) from None
584
+ raise
585
+ await asyncio.sleep(
586
+ self.retry.delay(attempt, getattr(e, "retry_after", None)))
587
+ raise AssertionError("unreachable")
588
+
589
+ async def request_approval(self, run_id: str, call_id: str, tool: str,
590
+ arguments: dict | None = None,
591
+ reasoning: str | None = None,
592
+ framework: str | None = None,
593
+ deadline_ms: int | None = None,
594
+ callback_url: str | None = None,
595
+ supersedes: str | None = None) -> str:
596
+ body = {"run_id": run_id, "call_id": call_id, "tool": tool,
597
+ "arguments": arguments or {}, "reasoning": reasoning}
598
+ if framework is not None:
599
+ body["framework"] = framework
600
+ if supersedes is not None:
601
+ body["supersedes"] = supersedes
602
+ if deadline_ms is not None:
603
+ body["deadline_ms"] = deadline_ms
604
+ if callback_url is not None:
605
+ body["callback_url"] = callback_url
606
+ out = await self._call("POST", "/api/approvals", body)
607
+ return out["approval_id"]
608
+
609
+ async def get(self, approval_id: str) -> dict:
610
+ return await self._call("GET", f"/api/approvals/{_p(approval_id)}")
611
+
612
+ async def list(self, status: str | None = None, limit: int = 100,
613
+ cursor: int = 0) -> list:
614
+ q = f"?limit={limit}&cursor={cursor}"
615
+ if status:
616
+ q += f"&status={_p(status)}"
617
+ return await self._call("GET", f"/api/approvals{q}")
618
+
619
+ async def wait_for_decision(self, approval_id: str, interval: float = 1.0,
620
+ timeout: float | None = None,
621
+ cancel=None,
622
+ max_interval: float | None = None) -> dict:
623
+ """See PrimaryPathClient.wait_for_decision. `cancel` is an
624
+ asyncio.Event; cancelling the awaiting task works as well."""
625
+ import asyncio
626
+
627
+ start = time.monotonic()
628
+ current = interval
629
+ ceiling = max_interval if max_interval is not None else interval
630
+ while True:
631
+ if cancel is not None and cancel.is_set():
632
+ raise WaitCancelled(approval_id)
633
+ try:
634
+ a = await self.get(approval_id)
635
+ if a.get("status") != "pending": # any terminal status
636
+ return a
637
+ except (ApiError, TransportError) as e:
638
+ if not _is_transient(e, self.retry):
639
+ raise
640
+ if timeout is not None and time.monotonic() - start > timeout:
641
+ raise DecisionTimeout(f"no decision on {approval_id} in {timeout}s")
642
+ pause = random.uniform(current * 0.8, current * 1.2)
643
+ if cancel is not None:
644
+ # asyncio.wait (not wait_for): no TimeoutError to catch, and
645
+ # on 3.10 asyncio.TimeoutError is not the builtin one
646
+ waiter = asyncio.ensure_future(cancel.wait())
647
+ done, _ = await asyncio.wait({waiter}, timeout=pause)
648
+ if not done:
649
+ waiter.cancel()
650
+ if cancel.is_set():
651
+ raise WaitCancelled(approval_id)
652
+ else:
653
+ await asyncio.sleep(pause)
654
+ current = min(ceiling, current * 1.5)
655
+
656
+ async def decide(self, approval_id: str, approved: bool, reviewer: str,
657
+ reason: str = "", idempotency_key: str | None = None) -> dict:
658
+ return await self._call("POST", f"/api/approvals/{_p(approval_id)}/decision",
659
+ {"approved": approved, "reviewer": reviewer,
660
+ "reason": reason}, idem=_key(idempotency_key))
661
+
662
+ async def annotate(self, approval_id: str, reviewer: str, note: str,
663
+ idempotency_key: str | None = None) -> dict:
664
+ return await self._call("POST", f"/api/approvals/{_p(approval_id)}/annotate",
665
+ {"reviewer": reviewer, "note": note},
666
+ idem=_key(idempotency_key))
667
+
668
+ async def cancel(self, approval_id: str, reason: str = "",
669
+ idempotency_key: str | None = None) -> dict:
670
+ return await self._call("POST", f"/api/approvals/{_p(approval_id)}/cancel",
671
+ {"reason": reason}, idem=_key(idempotency_key))
672
+
673
+ async def request_changes(self, approval_id: str, reviewer: str,
674
+ reason: str, idempotency_key: str | None = None) -> dict:
675
+ return await self._call(
676
+ "POST", f"/api/approvals/{_p(approval_id)}/request-changes",
677
+ {"reviewer": reviewer, "reason": reason}, idem=_key(idempotency_key))
678
+
679
+ async def report_incident(self, approval_id: str, reviewer: str,
680
+ summary: str, severity: str = "sev3",
681
+ idempotency_key: str | None = None) -> dict:
682
+ return await self._call("POST", f"/api/approvals/{_p(approval_id)}/incident",
683
+ {"reviewer": reviewer, "summary": summary,
684
+ "severity": severity}, idem=_key(idempotency_key))
685
+
686
+ async def redeem_grant(self, approval_id: str, nonce: str,
687
+ instance: str | None = None,
688
+ idempotency_key: str | None = None) -> dict:
689
+ """Retried under one Idempotency-Key; see PrimaryPathClient.redeem_grant."""
690
+ body = {"nonce": nonce}
691
+ if instance is not None:
692
+ body["instance"] = instance
693
+ return await self._call("POST", f"/api/approvals/{_p(approval_id)}/redeem",
694
+ body, idem=_key(idempotency_key))
695
+
696
+ async def signing_keys(self) -> dict[str, str]:
697
+ return (await self._call("GET", "/api/audit/keys"))["keys"]
698
+
699
+ async def ingest_run_events(self, run_id: str, events: list[dict],
700
+ idempotency_key: str | None = None) -> int:
701
+ out = await self._call("POST", f"/api/runs/{_p(run_id)}/events",
702
+ {"events": events}, idem=_key(idempotency_key))
703
+ return out.get("ingested", 0)
704
+
705
+ async def run_audit(self, run_id: str) -> list:
706
+ return await self._call("GET", f"/api/runs/{_p(run_id)}/audit")
707
+
708
+ async def export_audit(self) -> dict:
709
+ """The whole log: {"chains": [...]}, each chain independently
710
+ verifiable (F24)."""
711
+ return await self._call("GET", "/api/audit/export")
712
+
713
+ async def export_agent_audit(self, agent: str) -> dict:
714
+ """One agent's chain, signed under its own evidence profile (F24)."""
715
+ return await self._call("GET", f"/api/audit/export?agent={_p(agent)}")
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: primarypath-sdk
3
+ Version: 1.0.0rc1
4
+ Summary: Primary Path client SDK: govern any agent that can make two HTTP calls
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ License-File: LICENSE
8
+ Provides-Extra: async
9
+ Requires-Dist: httpx>=0.27; extra == "async"
10
+ Provides-Extra: grants
11
+ Requires-Dist: cryptography>=42; extra == "grants"
12
+ Dynamic: license-file
@@ -0,0 +1,6 @@
1
+ primarypath_client/__init__.py,sha256=qjcHhlfsfp10J0_T9sIWf1ebPeGod8y3f-20M3d3lu4,32579
2
+ primarypath_sdk-1.0.0rc1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
3
+ primarypath_sdk-1.0.0rc1.dist-info/METADATA,sha256=IW48URkk4tO_L6-bItPw8oMYTq9PzgMuzuf23kvbBKA,382
4
+ primarypath_sdk-1.0.0rc1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ primarypath_sdk-1.0.0rc1.dist-info/top_level.txt,sha256=-gR54ltpNqXYJ7g_9wlcXPh025hUHgOBWGBe5ivaXoI,19
6
+ primarypath_sdk-1.0.0rc1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ primarypath_client