pulr-sdk 0.4.0__tar.gz

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,3 @@
1
+ data/
2
+ node_modules/
3
+ .DS_Store
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: pulr-sdk
3
+ Version: 0.4.0
4
+ Summary: Official Python SDK for pulr.ai — secure file exchange for AI agents: upload, share, fetch, approve, and verify files with provenance, scanning, capability URLs, and signed receipts.
5
+ Project-URL: Homepage, https://pulr.ai
6
+ Project-URL: Repository, https://github.com/taleilon/pulr
7
+ Project-URL: Issues, https://github.com/taleilon/pulr/issues
8
+ Author: Tal Eilon
9
+ License-Expression: MIT
10
+ Keywords: ai-agents,artifacts,capability-urls,file-exchange,langchain,provenance,pulr
11
+ Requires-Python: >=3.9
12
+ Provides-Extra: langchain
13
+ Requires-Dist: langchain-core>=0.1; extra == 'langchain'
14
+ Provides-Extra: verify
15
+ Requires-Dist: cryptography>=41; extra == 'verify'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # pulr-sdk
19
+
20
+ Official Python SDK for [pulr.ai](https://pulr.ai) — secure file exchange for AI agents. Zero runtime dependencies; downloads are SHA-256-verified client-side.
21
+
22
+ ```bash
23
+ pip install pulr-sdk # core (stdlib only)
24
+ pip install pulr-sdk[verify] # + Ed25519 receipt verification
25
+ pip install pulr-sdk[langchain] # + LangChain tools
26
+ ```
27
+
28
+ ```python
29
+ from pulr import PulrClient, verify_receipt
30
+
31
+ pulr = PulrClient() # reads PULR_API_KEY
32
+
33
+ artifact = pulr.upload(
34
+ file_path="q3-report.pdf",
35
+ expires_in="48h",
36
+ approval=True, # link stays dormant until a human approves on the review page
37
+ provenance={"workflow": "quarterly-report", "model": "claude-fable-5"},
38
+ restrictions={"allow_countries": ["US"]},
39
+ )
40
+ print(artifact["review_url"])
41
+
42
+ # once approved — anyone with the link fetches, integrity-verified
43
+ data, sha256 = pulr.fetch_capability(artifact["download_url"])
44
+
45
+ # Ed25519-signed proof of hash + provenance + scan + approval
46
+ receipt = pulr.receipt(artifact["artifact_id"])
47
+ assert verify_receipt(receipt) # needs [verify] extra
48
+ ```
49
+
50
+ LangChain agents:
51
+
52
+ ```python
53
+ from pulr.langchain_tool import pulr_tools
54
+ tools = pulr_tools(PulrClient()) # pulr_upload / pulr_fetch / pulr_share StructuredTools
55
+ ```
56
+
57
+ Full API: `upload`, `get`, `download`, `fetch_capability`, `share`, `list`, `revoke`, `receipt` / `verify_receipt`, `whoami`, `usage`, `audit`, `create_key`, `set_webhook`. Get a workspace + key at [pulr.ai/app](https://pulr.ai/app).
58
+
59
+ MIT © Tal Eilon
60
+
61
+ ## Sealed handoff — no link at all
62
+
63
+ When the recipient has a pulr workspace, send straight to their address (`pa_...`):
64
+
65
+ ```python
66
+ pulr.send("pa_...", file_path="deck.pdf", message="final version")
67
+
68
+ # recipient side
69
+ offers = pulr.inbox() # sender, agent id, Ed25519 status, scan, sha256
70
+ pulr.accept(offers[0]["offer_id"]) # integrity-verified copy enters the workspace
71
+ # or: pulr.reject(offers[0]["offer_id"])
72
+
73
+ pulr.address() # your own receiving address
74
+ pulr.set_address(rotate=True) # old address dies instantly
75
+ ```
76
+
77
+ No capability URL is ever created; both sides' receipts carry a `handoff` block.
@@ -0,0 +1,60 @@
1
+ # pulr-sdk
2
+
3
+ Official Python SDK for [pulr.ai](https://pulr.ai) — secure file exchange for AI agents. Zero runtime dependencies; downloads are SHA-256-verified client-side.
4
+
5
+ ```bash
6
+ pip install pulr-sdk # core (stdlib only)
7
+ pip install pulr-sdk[verify] # + Ed25519 receipt verification
8
+ pip install pulr-sdk[langchain] # + LangChain tools
9
+ ```
10
+
11
+ ```python
12
+ from pulr import PulrClient, verify_receipt
13
+
14
+ pulr = PulrClient() # reads PULR_API_KEY
15
+
16
+ artifact = pulr.upload(
17
+ file_path="q3-report.pdf",
18
+ expires_in="48h",
19
+ approval=True, # link stays dormant until a human approves on the review page
20
+ provenance={"workflow": "quarterly-report", "model": "claude-fable-5"},
21
+ restrictions={"allow_countries": ["US"]},
22
+ )
23
+ print(artifact["review_url"])
24
+
25
+ # once approved — anyone with the link fetches, integrity-verified
26
+ data, sha256 = pulr.fetch_capability(artifact["download_url"])
27
+
28
+ # Ed25519-signed proof of hash + provenance + scan + approval
29
+ receipt = pulr.receipt(artifact["artifact_id"])
30
+ assert verify_receipt(receipt) # needs [verify] extra
31
+ ```
32
+
33
+ LangChain agents:
34
+
35
+ ```python
36
+ from pulr.langchain_tool import pulr_tools
37
+ tools = pulr_tools(PulrClient()) # pulr_upload / pulr_fetch / pulr_share StructuredTools
38
+ ```
39
+
40
+ Full API: `upload`, `get`, `download`, `fetch_capability`, `share`, `list`, `revoke`, `receipt` / `verify_receipt`, `whoami`, `usage`, `audit`, `create_key`, `set_webhook`. Get a workspace + key at [pulr.ai/app](https://pulr.ai/app).
41
+
42
+ MIT © Tal Eilon
43
+
44
+ ## Sealed handoff — no link at all
45
+
46
+ When the recipient has a pulr workspace, send straight to their address (`pa_...`):
47
+
48
+ ```python
49
+ pulr.send("pa_...", file_path="deck.pdf", message="final version")
50
+
51
+ # recipient side
52
+ offers = pulr.inbox() # sender, agent id, Ed25519 status, scan, sha256
53
+ pulr.accept(offers[0]["offer_id"]) # integrity-verified copy enters the workspace
54
+ # or: pulr.reject(offers[0]["offer_id"])
55
+
56
+ pulr.address() # your own receiving address
57
+ pulr.set_address(rotate=True) # old address dies instantly
58
+ ```
59
+
60
+ No capability URL is ever created; both sides' receipts carry a `handoff` block.
@@ -0,0 +1,277 @@
1
+ """pulr-sdk — official Python client for pulr.ai, secure file exchange for AI agents.
2
+
3
+ Zero runtime dependencies (urllib). Optional extras:
4
+ pip install pulr-sdk[verify] -> Ed25519 receipt verification (cryptography)
5
+ pip install pulr-sdk[langchain] -> LangChain tools (see pulr.langchain_tool)
6
+ """
7
+
8
+ import base64
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import urllib.error
13
+ import urllib.request
14
+ from urllib.parse import urlencode
15
+
16
+ __version__ = "0.4.0"
17
+ __all__ = ["PulrClient", "PulrError", "verify_receipt"]
18
+
19
+
20
+ class PulrError(Exception):
21
+ def __init__(self, status, code, message):
22
+ super().__init__(f"pulr {status}: {message or code}")
23
+ self.status = status
24
+ self.code = code
25
+
26
+
27
+ class PulrClient:
28
+ def __init__(self, api_key=None, base_url="https://pulr.ai", agent_key_pem=None):
29
+ """agent_key_pem: Ed25519 private key (PKCS8 PEM) registered with the workspace;
30
+ when set, uploads are signed automatically -> provenance.verified: true.
31
+ Requires: pip install pulr-sdk[verify]"""
32
+ self.api_key = api_key or os.environ.get("PULR_API_KEY")
33
+ if not self.api_key:
34
+ raise ValueError("PulrClient: api_key required (or set PULR_API_KEY)")
35
+ self.base_url = base_url.rstrip("/")
36
+ self.agent_key_pem = agent_key_pem
37
+
38
+ def _sign_manifest(self, raw):
39
+ if not self.agent_key_pem:
40
+ return None
41
+ try:
42
+ from cryptography.hazmat.primitives.serialization import load_pem_private_key, Encoding, PublicFormat
43
+ except ImportError as e:
44
+ raise ImportError("signed uploads need: pip install pulr-sdk[verify]") from e
45
+ priv = load_pem_private_key(self.agent_key_pem.encode() if isinstance(self.agent_key_pem, str) else self.agent_key_pem, password=None)
46
+ pub_der = priv.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
47
+ fingerprint = "ak_" + hashlib.sha256(pub_der).hexdigest()[:16]
48
+ sig = priv.sign(("pulr-manifest-v1\n" + hashlib.sha256(raw).hexdigest()).encode())
49
+ return {"key": fingerprint, "sig_b64": base64.b64encode(sig).decode()}
50
+
51
+ def _req(self, method, path, body=None, raw=False):
52
+ req = urllib.request.Request(self.base_url + path, method=method)
53
+ req.add_header("Authorization", f"Bearer {self.api_key}")
54
+ req.add_header("User-Agent", f"pulr-sdk-python/{__version__}")
55
+ data = None
56
+ if body is not None:
57
+ data = json.dumps(body).encode()
58
+ req.add_header("Content-Type", "application/json")
59
+ try:
60
+ with urllib.request.urlopen(req, data=data, timeout=60) as r:
61
+ payload = r.read()
62
+ return payload if raw else json.loads(payload)
63
+ except urllib.error.HTTPError as e:
64
+ try:
65
+ d = json.loads(e.read())
66
+ except Exception:
67
+ d = {}
68
+ raise PulrError(e.code, d.get("error"), d.get("message")) from None
69
+
70
+ # -- core --
71
+
72
+ def upload(self, content=None, file_path=None, filename=None, mime_type=None,
73
+ visibility="capability", expires_in="24h", max_downloads=None,
74
+ approval=False, description=None, tags=None, provenance=None,
75
+ restrictions=None, notify=None):
76
+ """Upload bytes/str/file. Returns the artifact dict (download_url, review_url, scan, ...)."""
77
+ if file_path:
78
+ with open(file_path, "rb") as f:
79
+ raw = f.read()
80
+ filename = filename or os.path.basename(file_path)
81
+ elif isinstance(content, bytes):
82
+ raw = content
83
+ elif isinstance(content, str):
84
+ raw = content.encode()
85
+ else:
86
+ raise ValueError("upload: content or file_path required")
87
+ body = {
88
+ "filename": filename or "artifact.bin",
89
+ "content_base64": base64.b64encode(raw).decode(),
90
+ "signature": self._sign_manifest(raw),
91
+ "mime_type": mime_type,
92
+ "visibility": visibility,
93
+ "expires_in": expires_in,
94
+ "max_downloads": max_downloads,
95
+ "description": description,
96
+ "tags": tags,
97
+ "provenance": provenance,
98
+ "restrictions": restrictions,
99
+ "notify": notify,
100
+ }
101
+ if approval:
102
+ body["approval"] = True
103
+ return self._req("POST", "/v1/artifacts", body)
104
+
105
+ def get(self, artifact_id):
106
+ return self._req("GET", f"/v1/artifacts/{artifact_id}")
107
+
108
+ def download(self, artifact_id):
109
+ """Download with client-side sha256 verification. Returns (bytes, sha256)."""
110
+ meta = self.get(artifact_id)
111
+ raw = self._req("GET", f"/v1/artifacts/{artifact_id}/download", raw=True)
112
+ digest = hashlib.sha256(raw).hexdigest()
113
+ if digest != meta["sha256"]:
114
+ raise PulrError(500, "integrity_failure", f"expected {meta['sha256']}, got {digest}")
115
+ return raw, digest
116
+
117
+ def fetch_capability(self, capability_url):
118
+ """Fetch a capability URL (no auth). Returns (bytes, sha256), integrity-verified."""
119
+ req = urllib.request.Request(capability_url)
120
+ req.add_header("User-Agent", f"pulr-sdk-python/{__version__}")
121
+ try:
122
+ with urllib.request.urlopen(req, timeout=60) as r:
123
+ raw = r.read()
124
+ expected = r.headers.get("x-pulr-sha256")
125
+ except urllib.error.HTTPError as e:
126
+ try:
127
+ d = json.loads(e.read())
128
+ except Exception:
129
+ d = {}
130
+ raise PulrError(e.code, d.get("error"), d.get("message")) from None
131
+ digest = hashlib.sha256(raw).hexdigest()
132
+ if expected and digest != expected:
133
+ raise PulrError(500, "integrity_failure", f"expected {expected}, got {digest}")
134
+ return raw, digest
135
+
136
+ # -- sealed handoff (workspace addresses) --
137
+
138
+ def send(self, to, content=None, file_path=None, filename=None, mime_type=None, message=None):
139
+ """Sealed handoff: send a file to another workspace by its pa_ address.
140
+ No download link ever exists — the recipient reviews and accepts it."""
141
+ if not to:
142
+ raise ValueError("send: to (pa_... workspace address) required")
143
+ if file_path:
144
+ with open(file_path, "rb") as f:
145
+ raw = f.read()
146
+ filename = filename or os.path.basename(file_path)
147
+ elif isinstance(content, bytes):
148
+ raw = content
149
+ elif isinstance(content, str):
150
+ raw = content.encode()
151
+ else:
152
+ raise ValueError("send: content or file_path required")
153
+ return self._req("POST", "/v1/artifacts", {
154
+ "filename": filename or "artifact.bin",
155
+ "content_base64": base64.b64encode(raw).decode(),
156
+ "signature": self._sign_manifest(raw),
157
+ "mime_type": mime_type,
158
+ "to": to,
159
+ "message": message,
160
+ })
161
+
162
+ def inbox(self, status=None):
163
+ """Offers made to this workspace via its address (default: awaiting acceptance)."""
164
+ q = f"?status={status}" if status else ""
165
+ return self._req("GET", f"/v1/inbox{q}")["offers"]
166
+
167
+ def accept(self, offer_id):
168
+ """Accept an offered file (integrity-verified copy + signed handoff receipt)."""
169
+ return self._req("POST", f"/v1/inbox/{offer_id}/accept", {})
170
+
171
+ def reject(self, offer_id):
172
+ """Decline an offered file."""
173
+ return self._req("POST", f"/v1/inbox/{offer_id}/reject", {})
174
+
175
+ def address(self):
176
+ """This workspace's receiving address (pa_...); minted on first call."""
177
+ return self._req("GET", "/v1/workspaces/address")
178
+
179
+ def set_address(self, rotate=False, paused=None):
180
+ """Rotate the address (old one dies) or pause/resume inbound offers."""
181
+ if rotate:
182
+ return self._req("POST", "/v1/workspaces/address", {"rotate": True})
183
+ return self._req("POST", "/v1/workspaces/address", {"paused": bool(paused)})
184
+
185
+ def share(self, artifact_id, expires_in=None, max_downloads=None, recipient=None, restrictions=None, notify=None):
186
+ return self._req("POST", f"/v1/artifacts/{artifact_id}/share", {
187
+ "expires_in": expires_in, "max_downloads": max_downloads,
188
+ "recipient": recipient, "restrictions": restrictions, "notify": notify,
189
+ })
190
+
191
+ def list(self, *, workspace_id=None, status=None, direction=None, tag=None, limit=None, offset=None):
192
+ """List files. Defaults to the key's own workspace; pass workspace_id to read a
193
+ sibling workspace on the same account (needs an account-scoped key)."""
194
+ q = {}
195
+ if workspace_id: q["workspace"] = workspace_id
196
+ if status: q["status"] = status
197
+ if direction: q["direction"] = direction
198
+ if tag: q["tag"] = tag
199
+ if limit: q["limit"] = limit
200
+ if offset: q["offset"] = offset
201
+ return self._req("GET", "/v1/artifacts" + ("?" + urlencode(q) if q else ""))["artifacts"]
202
+
203
+ # ---- workspaces (account-scoped key required) ----
204
+
205
+ def workspaces(self):
206
+ """Every workspace on this account, with address, file count and inbox depth."""
207
+ return self._req("GET", "/v1/account/workspaces")["workspaces"]
208
+
209
+ def create_workspace(self, name, *, key_name=None, agent_id=None):
210
+ """Create a workspace. Returns its id, receiving address and owner key (shown once)."""
211
+ return self._req("POST", "/v1/account/workspaces", {"name": name, "key_name": key_name, "agent_id": agent_id})
212
+
213
+ _UNSET = object()
214
+
215
+ def update_workspace(self, workspace_id, *, name=None, rotate_address=None, address_paused=None,
216
+ delivery_policy=None, trusted_senders=None, auto_max_bytes=_UNSET):
217
+ """Rename a workspace, rotate its address, pause deliveries, or set its delivery policy.
218
+
219
+ delivery_policy: "hold" (every offer waits for review) or "auto" (clean files
220
+ from trusted_senders are accepted instantly; flagged files always hold).
221
+ trusted_senders: full trust list — pa_ addresses and/or verified agent-key fingerprints.
222
+ """
223
+ body = {}
224
+ if name is not None: body["name"] = name
225
+ if rotate_address is not None: body["rotate_address"] = rotate_address
226
+ if address_paused is not None: body["address_paused"] = address_paused
227
+ if delivery_policy is not None: body["delivery_policy"] = delivery_policy
228
+ if trusted_senders is not None: body["trusted_senders"] = trusted_senders
229
+ if auto_max_bytes is not self._UNSET: body["auto_max_bytes"] = auto_max_bytes
230
+ return self._req("PATCH", f"/v1/account/workspaces/{workspace_id}", body)
231
+
232
+ def delete_workspace(self, workspace_id, confirm):
233
+ """Permanently delete a workspace and everything in it. `confirm` must equal its name."""
234
+ return self._req("DELETE", f"/v1/account/workspaces/{workspace_id}", {"confirm": confirm})
235
+
236
+ def revoke(self, artifact_id=None, capability_url=None):
237
+ return self._req("POST", "/v1/capabilities/revoke", {
238
+ "artifact_id": artifact_id, "capability_url": capability_url,
239
+ })
240
+
241
+ def receipt(self, artifact_id):
242
+ """Ed25519-signed audit receipt. Verify with pulr.verify_receipt()."""
243
+ return self._req("GET", f"/v1/artifacts/{artifact_id}/receipt")
244
+
245
+ # -- workspace --
246
+
247
+ def whoami(self):
248
+ return self._req("GET", "/v1/whoami")
249
+
250
+ def usage(self):
251
+ return self._req("GET", "/v1/usage")
252
+
253
+ def audit(self, artifact_id):
254
+ return self._req("GET", f"/v1/artifacts/{artifact_id}/audit")
255
+
256
+ def create_key(self, name, agent_id=None):
257
+ return self._req("POST", "/v1/keys", {"name": name, "agent_id": agent_id})
258
+
259
+ def set_webhook(self, url):
260
+ return self._req("POST", "/v1/workspaces/webhook", {"url": url})
261
+
262
+
263
+ def verify_receipt(receipt_response):
264
+ """Verify an Ed25519-signed receipt. Requires: pip install pulr-sdk[verify]."""
265
+ try:
266
+ from cryptography.hazmat.primitives.serialization import load_pem_public_key
267
+ from cryptography.exceptions import InvalidSignature
268
+ except ImportError as e:
269
+ raise ImportError("receipt verification needs the 'cryptography' package: pip install pulr-sdk[verify]") from e
270
+ key = load_pem_public_key(receipt_response["public_key_pem"].encode())
271
+ # compact separators match JavaScript's JSON.stringify byte-for-byte (key order is preserved)
272
+ payload = json.dumps(receipt_response["receipt"], separators=(",", ":"), ensure_ascii=False)
273
+ try:
274
+ key.verify(base64.b64decode(receipt_response["signature_b64"]), payload.encode())
275
+ return True
276
+ except InvalidSignature:
277
+ return False
@@ -0,0 +1,44 @@
1
+ """LangChain tools for pulr.ai. Requires: pip install pulr-sdk[langchain]
2
+
3
+ from pulr import PulrClient
4
+ from pulr.langchain_tool import pulr_tools
5
+
6
+ tools = pulr_tools(PulrClient()) # reads PULR_API_KEY
7
+ # -> [pulr_upload, pulr_fetch, pulr_share] StructuredTools for any agent
8
+ """
9
+
10
+ import json
11
+
12
+
13
+ def pulr_tools(client):
14
+ try:
15
+ from langchain_core.tools import StructuredTool
16
+ except ImportError as e:
17
+ raise ImportError("LangChain tools need langchain-core: pip install pulr-sdk[langchain]") from e
18
+
19
+ def upload(content: str, filename: str = "artifact.txt", expires_in: str = "24h",
20
+ approval: bool = False, description: str = "") -> str:
21
+ """Upload text content to pulr.ai. Returns JSON with download_url (capability link),
22
+ review_url (human review page), sha256, and scan verdict. Set approval=True to hold
23
+ the link until a human approves on the review page."""
24
+ a = client.upload(content=content, filename=filename, expires_in=expires_in,
25
+ approval=approval, description=description or None)
26
+ return json.dumps({k: a[k] for k in ("artifact_id", "download_url", "review_url", "sha256", "status")})
27
+
28
+ def fetch(capability_url: str) -> str:
29
+ """Fetch a pulr.ai capability URL and return its text content (sha256-verified)."""
30
+ raw, digest = client.fetch_capability(capability_url)
31
+ try:
32
+ return raw.decode()
33
+ except UnicodeDecodeError:
34
+ return f"<binary {len(raw)} bytes, sha256 {digest}>"
35
+
36
+ def share(artifact_id: str, expires_in: str = "24h", max_downloads: int = 1) -> str:
37
+ """Create a fresh capability URL for an existing pulr.ai artifact (defaults to burn-after-reading)."""
38
+ return json.dumps(client.share(artifact_id, expires_in=expires_in, max_downloads=max_downloads))
39
+
40
+ return [
41
+ StructuredTool.from_function(upload, name="pulr_upload"),
42
+ StructuredTool.from_function(fetch, name="pulr_fetch"),
43
+ StructuredTool.from_function(share, name="pulr_share"),
44
+ ]
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pulr-sdk"
7
+ version = "0.4.0"
8
+ description = "Official Python SDK for pulr.ai — secure file exchange for AI agents: upload, share, fetch, approve, and verify files with provenance, scanning, capability URLs, and signed receipts."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "Tal Eilon" }]
13
+ keywords = ["pulr", "ai-agents", "file-exchange", "artifacts", "capability-urls", "provenance", "langchain"]
14
+
15
+ [project.optional-dependencies]
16
+ verify = ["cryptography>=41"]
17
+ langchain = ["langchain-core>=0.1"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://pulr.ai"
21
+ Repository = "https://github.com/taleilon/pulr"
22
+ Issues = "https://github.com/taleilon/pulr/issues"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["pulr"]