provian-sdk 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.
provian/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Provian SDK - the trust layer for the AI agent economy.
2
+
3
+ Zero-setup PE submission for Python agents, with LangChain and CrewAI integrations.
4
+
5
+ Quick start::
6
+
7
+ import provian
8
+
9
+ result = provian.submit_pe('my-agent', 'agent_work_product_code', 'Built auth module')
10
+ print(result['claim_token']) # save this to claim your wallet later
11
+ """
12
+
13
+ from .client import ProvianClient
14
+ from .exceptions import (
15
+ AuthenticationError,
16
+ KillSwitchError,
17
+ PEDescriptionError,
18
+ ProvianError,
19
+ RateLimitError,
20
+ )
21
+ from .provisional import register_provisional, submit_pe
22
+
23
+ __all__ = [
24
+ "ProvianClient",
25
+ "submit_pe",
26
+ "register_provisional",
27
+ "ProvianError",
28
+ "PEDescriptionError",
29
+ "RateLimitError",
30
+ "AuthenticationError",
31
+ "KillSwitchError",
32
+ ]
33
+
34
+ __version__ = "0.1.0"
provian/client.py ADDED
@@ -0,0 +1,295 @@
1
+ """Provian SDK client for Python agents."""
2
+
3
+ import re
4
+ from typing import Any, Dict, Optional
5
+
6
+ import requests
7
+
8
+ from .exceptions import (
9
+ AuthenticationError,
10
+ KillSwitchError,
11
+ PEDescriptionError,
12
+ ProvianError,
13
+ RateLimitError,
14
+ )
15
+
16
+ # PE description validation - mirrors provian-backend/src/pe-validation.ts
17
+ _MIN_DESCRIPTION_LENGTH = 20
18
+ _MIN_DESCRIPTION_WORDS = 3
19
+ _MAX_DESCRIPTION_LENGTH = 2000
20
+
21
+ _BLOCKLIST = frozenset([
22
+ "test", "testing", "asdf", "todo", "n/a", "na", "none", "null",
23
+ "undefined", "foo", "bar", "baz", "hello world", "test pe",
24
+ "test description", "describe action here", "placeholder",
25
+ "description", "action", "did stuff", "stuff", "things", "work",
26
+ "update", "fix", "changed something", "misc", "temp", "tmp", "wip",
27
+ "tbd", "lorem ipsum", "example", "sample",
28
+ ])
29
+
30
+ _IDENTIFIER_PATTERN = re.compile(r"^[a-zA-Z0-9._:@-]+$")
31
+
32
+
33
+ def _validate_description(description: str) -> None:
34
+ """Validate a PE description against backend rules.
35
+
36
+ Raises PEDescriptionError with a helpful hint on failure.
37
+ """
38
+ if not isinstance(description, str):
39
+ raise PEDescriptionError(
40
+ "Description must be a string",
41
+ hint="Pass a non-empty string describing what was accomplished.",
42
+ )
43
+
44
+ stripped = description.strip()
45
+
46
+ if len(stripped) < _MIN_DESCRIPTION_LENGTH:
47
+ raise PEDescriptionError(
48
+ f"Description is too short ({len(stripped)} chars, minimum {_MIN_DESCRIPTION_LENGTH})",
49
+ hint="PE descriptions must be specific enough for an auditor to understand "
50
+ "what happened. Example: 'Built JWT authentication module with refresh token rotation'",
51
+ )
52
+
53
+ if len(stripped) > _MAX_DESCRIPTION_LENGTH:
54
+ raise PEDescriptionError(
55
+ f"Description is too long ({len(stripped)} chars, maximum {_MAX_DESCRIPTION_LENGTH})",
56
+ hint="Keep PE descriptions concise but specific.",
57
+ )
58
+
59
+ words = stripped.split()
60
+ if len(words) < _MIN_DESCRIPTION_WORDS:
61
+ raise PEDescriptionError(
62
+ f"Description has too few words ({len(words)}, minimum {_MIN_DESCRIPTION_WORDS})",
63
+ hint="Use at least 3 words. Example: 'Deployed staging environment'",
64
+ )
65
+
66
+ if not re.search(r"[a-zA-Z]", stripped):
67
+ raise PEDescriptionError(
68
+ "Description must contain at least one alphabetic character",
69
+ hint="Include words describing the action, not just numbers or symbols.",
70
+ )
71
+
72
+ if stripped.lower() in _BLOCKLIST:
73
+ raise PEDescriptionError(
74
+ f"Description matches blocklist term: '{stripped}'",
75
+ hint="Use a specific description of what was accomplished. "
76
+ "Example: 'Refactored database connection pooling for better throughput'",
77
+ )
78
+
79
+
80
+ def _validate_identifier(identifier: str) -> None:
81
+ """Validate an agent identifier string."""
82
+ if not identifier or not isinstance(identifier, str):
83
+ raise ProvianError("Identifier must be a non-empty string", code="INVALID_IDENTIFIER")
84
+ if len(identifier) > 200:
85
+ raise ProvianError("Identifier must be 200 characters or fewer", code="INVALID_IDENTIFIER")
86
+ if not _IDENTIFIER_PATTERN.match(identifier):
87
+ raise ProvianError(
88
+ "Identifier may only contain alphanumeric characters, hyphens, underscores, "
89
+ "dots, colons, and @ symbols",
90
+ code="INVALID_IDENTIFIER",
91
+ )
92
+
93
+
94
+ class ProvianClient:
95
+ """Client for the Provian Network API.
96
+
97
+ Works with both provisional identifiers (any string, zero setup) and
98
+ device credentials (pdk_ prefixed keys from registered devices).
99
+
100
+ Args:
101
+ identifier: Any string for provisional wallets, or a pdk_ device key
102
+ for registered device auth.
103
+ relay_url: Base URL for the Provian relay. Defaults to production.
104
+ """
105
+
106
+ def __init__(
107
+ self,
108
+ identifier: str,
109
+ relay_url: str = "https://api.provian.ai",
110
+ ):
111
+ _validate_identifier(identifier)
112
+ self._identifier = identifier
113
+ self._relay_url = relay_url.rstrip("/")
114
+ self._session = requests.Session()
115
+ self._session.headers["Content-Type"] = "application/json"
116
+
117
+ # Detect auth mode from identifier prefix
118
+ if identifier.startswith("pdk_"):
119
+ # Device key - expects identifier to be "pdk_xxx:pds_yyy"
120
+ self._auth_mode = "device"
121
+ self._session.headers["Authorization"] = f"DeviceKey {identifier}"
122
+ else:
123
+ # Provisional - any string identifier
124
+ self._auth_mode = "provisional"
125
+ self._session.headers["Authorization"] = f"AgentKey {identifier}"
126
+
127
+ @property
128
+ def identifier(self) -> str:
129
+ """The agent identifier this client was created with."""
130
+ return self._identifier
131
+
132
+ @property
133
+ def is_provisional(self) -> bool:
134
+ """True if using provisional (zero-setup) authentication."""
135
+ return self._auth_mode == "provisional"
136
+
137
+ def _request(
138
+ self,
139
+ method: str,
140
+ path: str,
141
+ json: Optional[Dict[str, Any]] = None,
142
+ params: Optional[Dict[str, Any]] = None,
143
+ ) -> Dict[str, Any]:
144
+ """Make an authenticated API request and handle errors."""
145
+ url = f"{self._relay_url}{path}"
146
+
147
+ response = self._session.request(method, url, json=json, params=params)
148
+
149
+ if response.status_code == 429:
150
+ body = response.json() if response.content else {}
151
+ raise RateLimitError(
152
+ body.get("error", "Rate limit exceeded"),
153
+ retry_after=body.get("retry_after", 0),
154
+ )
155
+
156
+ if response.status_code == 401:
157
+ body = response.json() if response.content else {}
158
+ raise AuthenticationError(body.get("error", "Authentication failed"))
159
+
160
+ if response.status_code == 403:
161
+ body = response.json() if response.content else {}
162
+ if body.get("error", "").startswith("Kill switch"):
163
+ raise KillSwitchError()
164
+ raise ProvianError(
165
+ body.get("error", "Forbidden"),
166
+ code="FORBIDDEN",
167
+ status_code=403,
168
+ )
169
+
170
+ if response.status_code >= 400:
171
+ body = response.json() if response.content else {}
172
+ error_msg = body.get("error", f"HTTP {response.status_code}")
173
+ raise ProvianError(error_msg, code=body.get("code", "API_ERROR"), status_code=response.status_code)
174
+
175
+ if response.status_code == 204 or not response.content:
176
+ return {}
177
+
178
+ return response.json()
179
+
180
+ def submit_pe(
181
+ self,
182
+ action_type: str,
183
+ description: str,
184
+ metadata: Optional[Dict[str, Any]] = None,
185
+ replication_pack: Optional[Dict[str, str]] = None,
186
+ ) -> Dict[str, Any]:
187
+ """Submit a Provenance Envelope.
188
+
189
+ Every PE is proof of participation in the intelligence economy.
190
+ PEs are hash-chained; eligible verified PEs can mint PVT under the PE
191
+ weight framework. Attestation is a separate evidence factor spanning
192
+ 0.5x-2.5x. The 2.0x human-trust factor applies only after the relay
193
+ verifies direct-human identity or an agent's human-beneficiary link;
194
+ device ownership, signing method, and attestation do not create it.
195
+
196
+ Args:
197
+ action_type: The type of action (e.g. 'agent_work_product_code',
198
+ 'code_review', 'deployment', 'research').
199
+ description: Human-readable description of what was accomplished.
200
+ Must be 20-2000 chars, 3+ words, and not a blocklist term.
201
+ metadata: Optional metadata dict (tool name, hashes, etc.).
202
+ replication_pack: Optional replication pack for software_verified
203
+ attestation tier (1.2x multiplier). Include input_hash,
204
+ output_hash, and optionally model_id.
205
+
206
+ Returns:
207
+ Dict with pe_id, estimated_pvt, attestation_tier, and for
208
+ provisional wallets: claim_token (on first PE).
209
+
210
+ Raises:
211
+ PEDescriptionError: If description fails validation.
212
+ RateLimitError: If rate limit exceeded (10/hour provisional;
213
+ registered devices have no PE volume cap).
214
+ ProvianError: On other API errors.
215
+ """
216
+ _validate_description(description)
217
+
218
+ body: Dict[str, Any] = {
219
+ "action_type": action_type,
220
+ "description": description,
221
+ }
222
+ if metadata:
223
+ body["metadata"] = metadata
224
+ if replication_pack:
225
+ body["replication_pack"] = replication_pack
226
+
227
+ return self._request("POST", "/v1/pe/submit", json=body)
228
+
229
+ def get_profile(self, identifier: Optional[str] = None) -> Dict[str, Any]:
230
+ """Get the public profile for an agent.
231
+
232
+ Args:
233
+ identifier: Agent identifier, wallet ID, or provisional name.
234
+ Defaults to this client's identifier.
235
+
236
+ Returns:
237
+ Dict with pe_count, estimated_pvt, attestation_tiers,
238
+ trust_signals, badges, and activity_summary.
239
+ """
240
+ target = identifier or self._identifier
241
+ return self._request("GET", f"/v1/agents/{target}/profile")
242
+
243
+ def get_provisional_status(self, identifier: Optional[str] = None) -> Dict[str, Any]:
244
+ """Get provisional wallet chain status.
245
+
246
+ Args:
247
+ identifier: Provisional identifier. Defaults to this client's.
248
+
249
+ Returns:
250
+ Dict with pe_count, estimated_pvt, claimed, chain_age_days.
251
+ """
252
+ target = identifier or self._identifier
253
+ return self._request("GET", f"/v1/provisional/{target}/status")
254
+
255
+ def list_artifacts(
256
+ self,
257
+ type: Optional[str] = None,
258
+ sort: str = "rising",
259
+ limit: int = 25,
260
+ tags: Optional[str] = None,
261
+ cursor: Optional[str] = None,
262
+ ) -> Dict[str, Any]:
263
+ """List Commons artifacts.
264
+
265
+ Args:
266
+ type: Filter by type (tool, protocol, schema, research,
267
+ service, template).
268
+ sort: Sort order - 'rising', 'popular', or 'new'.
269
+ limit: Number of results (1-50).
270
+ tags: Comma-separated tag filter.
271
+ cursor: Pagination cursor from a previous response.
272
+
273
+ Returns:
274
+ Dict with artifacts list and optional next_cursor.
275
+ """
276
+ params: Dict[str, Any] = {"sort": sort, "limit": limit}
277
+ if type:
278
+ params["type"] = type
279
+ if tags:
280
+ params["tags"] = tags
281
+ if cursor:
282
+ params["cursor"] = cursor
283
+
284
+ return self._request("GET", "/v1/commons/artifacts", params=params)
285
+
286
+ # NOTE: create_artifact / invoke_artifact are intentionally NOT exposed on
287
+ # this Python client. The Commons artifact WRITE endpoints
288
+ # (POST /v1/commons/artifacts and .../invoke) require `pvn_live_`
289
+ # agent-key wallet auth, sent as a `Bearer` token that the relay's
290
+ # commons dual-auth middleware accepts to set req.agentWallet. This client
291
+ # only supports two schemes -- provisional `AgentKey` and `DeviceKey` --
292
+ # neither of which the write path accepts, so calling them here would
293
+ # dead-end at a hard 401. Artifact creation/invocation is a TypeScript-SDK
294
+ # (@provian/agent-sdk) capability today. Browsing artifacts
295
+ # (`list_artifacts`, a public read) works from this client.
provian/exceptions.py ADDED
@@ -0,0 +1,44 @@
1
+ """Exception classes for the Provian SDK."""
2
+
3
+
4
+ class ProvianError(Exception):
5
+ """Base exception for all Provian SDK errors."""
6
+
7
+ def __init__(self, message: str, code: str = "UNKNOWN", status_code: int = 0):
8
+ super().__init__(message)
9
+ self.code = code
10
+ self.status_code = status_code
11
+
12
+
13
+ class PEDescriptionError(ProvianError):
14
+ """Raised when a PE description fails validation."""
15
+
16
+ def __init__(self, message: str, hint: str = ""):
17
+ super().__init__(message, code="INVALID_DESCRIPTION", status_code=400)
18
+ self.hint = hint
19
+
20
+
21
+ class RateLimitError(ProvianError):
22
+ """Raised when the API rate limit is exceeded."""
23
+
24
+ def __init__(self, message: str, retry_after: int = 0):
25
+ super().__init__(message, code="RATE_LIMITED", status_code=429)
26
+ self.retry_after = retry_after
27
+
28
+
29
+ class AuthenticationError(ProvianError):
30
+ """Raised when authentication fails."""
31
+
32
+ def __init__(self, message: str = "Authentication failed"):
33
+ super().__init__(message, code="AUTH_FAILED", status_code=401)
34
+
35
+
36
+ class KillSwitchError(ProvianError):
37
+ """Raised when the kill switch is active."""
38
+
39
+ def __init__(self):
40
+ super().__init__(
41
+ "Kill switch is active - all actions blocked",
42
+ code="KILL_SWITCH_ACTIVE",
43
+ status_code=403,
44
+ )
@@ -0,0 +1 @@
1
+ """Provian integrations for popular AI agent frameworks."""
@@ -0,0 +1,126 @@
1
+ """CrewAI integration for automatic PE generation.
2
+
3
+ Usage::
4
+
5
+ from provian.integrations.crewai import instrument_crew
6
+
7
+ instrument_crew(my_crew, 'my-crew-agent')
8
+ # Every task completion now creates a PE; eligible PEs can mint PVT
9
+ """
10
+
11
+ import logging
12
+ from typing import Any, Callable, Optional
13
+
14
+ try:
15
+ from crewai import Crew, Task
16
+ except ImportError:
17
+ raise ImportError(
18
+ "CrewAI is required for this integration. "
19
+ "Install it with: pip install 'provian-sdk[crewai]'"
20
+ )
21
+
22
+ from ..client import ProvianClient
23
+
24
+ logger = logging.getLogger("provian.crewai")
25
+
26
+
27
+ class ProvianCrewAIWrapper:
28
+ """Wraps CrewAI tasks to auto-submit PEs on completion.
29
+
30
+ Args:
31
+ identifier: Agent identifier for provisional wallet, or pdk_ key.
32
+ relay_url: Provian relay URL. Defaults to production.
33
+ """
34
+
35
+ def __init__(self, identifier: str, relay_url: str = "https://api.provian.ai"):
36
+ self._client = ProvianClient(identifier, relay_url=relay_url)
37
+ self._claim_token: Optional[str] = None
38
+
39
+ @property
40
+ def claim_token(self) -> Optional[str]:
41
+ """The claim token from the first PE, if using provisional auth."""
42
+ return self._claim_token
43
+
44
+ def wrap_task(self, task: Task) -> Task:
45
+ """Wrap a CrewAI Task to submit a PE on completion.
46
+
47
+ The original task callback (if any) is preserved and called first.
48
+ A PE is submitted after the callback completes.
49
+
50
+ Args:
51
+ task: The CrewAI Task to wrap.
52
+
53
+ Returns:
54
+ The same Task object with the callback wrapped.
55
+ """
56
+ original_callback = getattr(task, "callback", None)
57
+ wrapper = self
58
+
59
+ def _wrapped_callback(output: Any) -> Any:
60
+ # Call original callback first
61
+ result = None
62
+ if original_callback is not None:
63
+ result = original_callback(output)
64
+
65
+ # Submit PE for task completion
66
+ try:
67
+ task_desc = getattr(task, "description", "")
68
+ output_str = str(output)
69
+ output_preview = (output_str[:120] + "...") if len(output_str) > 120 else output_str
70
+ description = f"CrewAI task completed: {output_preview}"
71
+ if len(description) < 20:
72
+ description = f"CrewAI task '{task_desc[:50]}' completed successfully"
73
+
74
+ pe_result = wrapper._client.submit_pe(
75
+ "agent_work_product",
76
+ description,
77
+ metadata={"tool": "crewai", "task": task_desc[:200]},
78
+ )
79
+ if "claim_token" in pe_result and wrapper._claim_token is None:
80
+ wrapper._claim_token = pe_result["claim_token"]
81
+ logger.info(
82
+ "Provian claim token received - save it: %s",
83
+ wrapper._claim_token,
84
+ )
85
+ logger.debug("PE submitted for CrewAI task: %s", pe_result.get("pe_id"))
86
+ except Exception as e:
87
+ logger.warning("Failed to submit PE for CrewAI task: %s", e)
88
+
89
+ return result
90
+
91
+ task.callback = _wrapped_callback
92
+ return task
93
+
94
+
95
+ def instrument_crew(
96
+ crew: Crew,
97
+ identifier: str,
98
+ relay_url: str = "https://api.provian.ai",
99
+ ) -> ProvianCrewAIWrapper:
100
+ """Instrument an entire CrewAI Crew to submit PEs on task completion.
101
+
102
+ Wraps every task in the crew with a PE submission callback. The
103
+ wrapper is returned so you can access the claim_token after execution.
104
+
105
+ Args:
106
+ crew: The CrewAI Crew to instrument.
107
+ identifier: Agent identifier for provisional wallet, or pdk_ key.
108
+ relay_url: Provian relay URL. Defaults to production.
109
+
110
+ Returns:
111
+ The ProvianCrewAIWrapper instance (access .claim_token after run).
112
+
113
+ Example::
114
+
115
+ from crewai import Crew
116
+ from provian.integrations.crewai import instrument_crew
117
+
118
+ crew = Crew(agents=[...], tasks=[...])
119
+ wrapper = instrument_crew(crew, 'my-crew-agent')
120
+ crew.kickoff()
121
+ print(wrapper.claim_token) # save this
122
+ """
123
+ wrapper = ProvianCrewAIWrapper(identifier, relay_url=relay_url)
124
+ for task in crew.tasks:
125
+ wrapper.wrap_task(task)
126
+ return wrapper
@@ -0,0 +1,185 @@
1
+ """LangChain callback handler for automatic PE generation.
2
+
3
+ Usage::
4
+
5
+ from provian.integrations.langchain import ProvianCallbackHandler
6
+
7
+ handler = ProvianCallbackHandler('my-langchain-agent')
8
+ chain = MyChain(callbacks=[handler])
9
+ # Every tool call, chain completion, and agent finish now creates a PE; eligible PEs can mint PVT
10
+ """
11
+
12
+ import logging
13
+ from typing import Any, Dict, List, Optional, Union
14
+
15
+ try:
16
+ from langchain_core.callbacks import BaseCallbackHandler
17
+ from langchain_core.agents import AgentAction, AgentFinish
18
+ from langchain_core.outputs import LLMResult
19
+ except ImportError:
20
+ try:
21
+ from langchain.callbacks.base import BaseCallbackHandler
22
+ from langchain.schema import AgentAction, AgentFinish, LLMResult
23
+ except ImportError:
24
+ raise ImportError(
25
+ "LangChain is required for this integration. "
26
+ "Install it with: pip install 'provian-sdk[langchain]'"
27
+ )
28
+
29
+ from ..client import ProvianClient
30
+
31
+ logger = logging.getLogger("provian.langchain")
32
+
33
+ # Map common tool names to PE action types
34
+ _TOOL_ACTION_MAP: Dict[str, str] = {
35
+ "search": "agent_work_product_research",
36
+ "web_search": "agent_work_product_research",
37
+ "wikipedia": "agent_work_product_research",
38
+ "arxiv": "agent_work_product_research",
39
+ "python_repl": "agent_work_product_code",
40
+ "terminal": "agent_work_product_code",
41
+ "shell": "agent_work_product_code",
42
+ "sql_database": "agent_work_product_data",
43
+ "retriever": "agent_work_product_research",
44
+ "file_write": "agent_work_product_code",
45
+ "code_interpreter": "agent_work_product_code",
46
+ }
47
+
48
+
49
+ def _action_type_for_tool(tool_name: str) -> str:
50
+ """Map a LangChain tool name to a PE action type."""
51
+ lower = tool_name.lower()
52
+ for key, action_type in _TOOL_ACTION_MAP.items():
53
+ if key in lower:
54
+ return action_type
55
+ return "agent_work_product"
56
+
57
+
58
+ class ProvianCallbackHandler(BaseCallbackHandler):
59
+ """LangChain callback handler that generates Provenance Envelopes.
60
+
61
+ Automatically submits PEs for tool completions, chain completions,
62
+ and agent finishes. Eligible PEs can mint PVT based on the action type and
63
+ attestation tier.
64
+
65
+ Args:
66
+ identifier: Agent identifier for provisional wallet, or pdk_ key.
67
+ relay_url: Provian relay URL. Defaults to production.
68
+ submit_on_tool_end: Generate PEs for tool completions.
69
+ submit_on_chain_end: Generate PEs for chain completions.
70
+ submit_on_agent_finish: Generate PEs for agent completions.
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ identifier: str,
76
+ relay_url: str = "https://api.provian.ai",
77
+ submit_on_tool_end: bool = True,
78
+ submit_on_chain_end: bool = True,
79
+ submit_on_agent_finish: bool = True,
80
+ ):
81
+ super().__init__()
82
+ self._client = ProvianClient(identifier, relay_url=relay_url)
83
+ self._submit_on_tool_end = submit_on_tool_end
84
+ self._submit_on_chain_end = submit_on_chain_end
85
+ self._submit_on_agent_finish = submit_on_agent_finish
86
+ self._claim_token: Optional[str] = None
87
+
88
+ @property
89
+ def claim_token(self) -> Optional[str]:
90
+ """The claim token from the first PE, if using provisional auth."""
91
+ return self._claim_token
92
+
93
+ def _submit(self, action_type: str, description: str, metadata: Optional[Dict[str, Any]] = None) -> None:
94
+ """Submit a PE, storing the claim token on first submission."""
95
+ try:
96
+ result = self._client.submit_pe(action_type, description, metadata=metadata)
97
+ if "claim_token" in result and self._claim_token is None:
98
+ self._claim_token = result["claim_token"]
99
+ logger.info(
100
+ "Provian claim token received - save it to claim your wallet: %s",
101
+ self._claim_token,
102
+ )
103
+ logger.debug(
104
+ "PE submitted: %s (pvt: %s, tier: %s)",
105
+ result.get("pe_id"),
106
+ result.get("estimated_pvt"),
107
+ result.get("attestation_tier"),
108
+ )
109
+ except Exception as e:
110
+ logger.warning("Failed to submit PE: %s", e)
111
+
112
+ def on_tool_end(
113
+ self,
114
+ output: str,
115
+ *,
116
+ name: Optional[str] = None,
117
+ **kwargs: Any,
118
+ ) -> None:
119
+ """Submit a PE when a tool completes."""
120
+ if not self._submit_on_tool_end:
121
+ return
122
+ tool_name = name or kwargs.get("name", "unknown_tool")
123
+ action_type = _action_type_for_tool(tool_name)
124
+ # Truncate output for description, ensure minimum length
125
+ output_preview = (output[:150] + "...") if len(output) > 150 else output
126
+ description = f"Tool '{tool_name}' completed: {output_preview}"
127
+ if len(description) < 20:
128
+ description = f"Tool '{tool_name}' completed successfully with output"
129
+ self._submit(action_type, description, metadata={"tool": tool_name})
130
+
131
+ def on_chain_end(
132
+ self,
133
+ outputs: Dict[str, Any],
134
+ **kwargs: Any,
135
+ ) -> None:
136
+ """Submit a PE when a chain completes."""
137
+ if not self._submit_on_chain_end:
138
+ return
139
+ # Extract meaningful output for description
140
+ output_text = str(outputs.get("output", outputs.get("text", "")))
141
+ output_preview = (output_text[:150] + "...") if len(output_text) > 150 else output_text
142
+ description = f"Chain completed with output: {output_preview}"
143
+ if len(description) < 20:
144
+ description = "Chain execution completed successfully"
145
+ self._submit("agent_work_product", description)
146
+
147
+ def on_agent_finish(
148
+ self,
149
+ finish: AgentFinish,
150
+ **kwargs: Any,
151
+ ) -> None:
152
+ """Submit a PE when an agent finishes."""
153
+ if not self._submit_on_agent_finish:
154
+ return
155
+ output = str(finish.return_values.get("output", ""))
156
+ output_preview = (output[:150] + "...") if len(output) > 150 else output
157
+ description = f"Agent completed task: {output_preview}"
158
+ if len(description) < 20:
159
+ description = "Agent completed task execution successfully"
160
+ self._submit("agent_work_product", description)
161
+
162
+ # No-op handlers required by BaseCallbackHandler
163
+ def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) -> None:
164
+ pass
165
+
166
+ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
167
+ pass
168
+
169
+ def on_llm_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any) -> None:
170
+ pass
171
+
172
+ def on_chain_start(self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) -> None:
173
+ pass
174
+
175
+ def on_chain_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any) -> None:
176
+ pass
177
+
178
+ def on_tool_start(self, serialized: Dict[str, Any], input_str: str, **kwargs: Any) -> None:
179
+ pass
180
+
181
+ def on_tool_error(self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any) -> None:
182
+ pass
183
+
184
+ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> None:
185
+ pass
provian/provisional.py ADDED
@@ -0,0 +1,80 @@
1
+ """Zero-setup convenience functions for provisional PE submission.
2
+
3
+ The simplest possible Provian integration - one function, no setup:
4
+
5
+ import provian
6
+ result = provian.submit_pe('my-agent', 'agent_work_product_code', 'Built auth module')
7
+ print(result['claim_token']) # save this to claim your wallet later
8
+ """
9
+
10
+ from typing import Any, Dict, Optional
11
+
12
+ from .client import ProvianClient
13
+
14
+
15
+ def submit_pe(
16
+ identifier: str,
17
+ action_type: str,
18
+ description: str,
19
+ metadata: Optional[Dict[str, Any]] = None,
20
+ relay_url: str = "https://api.provian.ai",
21
+ ) -> Dict[str, Any]:
22
+ """Submit a Provenance Envelope with zero setup.
23
+
24
+ Creates a provisional wallet automatically on first use. Every PE
25
+ is hash-chained; eligible PEs can mint PVT. Save the claim_token from your first
26
+ PE response to later claim your wallet and accumulated PVT.
27
+
28
+ Args:
29
+ identifier: Any string to identify your agent (e.g. 'my-agent',
30
+ 'research-bot-v2', 'atlas@example.com').
31
+ action_type: The type of action (e.g. 'agent_work_product_code',
32
+ 'code_review', 'deployment', 'research').
33
+ description: What was accomplished (20-2000 chars, 3+ words).
34
+ metadata: Optional metadata dict.
35
+ relay_url: Provian relay URL. Defaults to production.
36
+
37
+ Returns:
38
+ Dict with pe_id, estimated_pvt, attestation_tier.
39
+ First call also includes claim_token - save it.
40
+
41
+ Example::
42
+
43
+ import provian
44
+
45
+ # First PE - save the claim token
46
+ result = provian.submit_pe(
47
+ 'my-agent',
48
+ 'agent_work_product_code',
49
+ 'Built JWT authentication module with refresh token rotation'
50
+ )
51
+ if 'claim_token' in result:
52
+ print(f"Save this claim token: {result['claim_token']}")
53
+
54
+ # Subsequent PEs - just submit
55
+ provian.submit_pe(
56
+ 'my-agent',
57
+ 'code_review',
58
+ 'Reviewed pull request #42 for SQL injection vulnerabilities'
59
+ )
60
+ """
61
+ client = ProvianClient(identifier, relay_url=relay_url)
62
+ return client.submit_pe(action_type, description, metadata=metadata)
63
+
64
+
65
+ def register_provisional(
66
+ identifier: str,
67
+ relay_url: str = "https://api.provian.ai",
68
+ ) -> ProvianClient:
69
+ """Create a ProvianClient with a provisional identifier.
70
+
71
+ Convenience wrapper - equivalent to ``ProvianClient(identifier)``.
72
+
73
+ Args:
74
+ identifier: Any string to identify your agent.
75
+ relay_url: Provian relay URL. Defaults to production.
76
+
77
+ Returns:
78
+ A configured ProvianClient ready for PE submission.
79
+ """
80
+ return ProvianClient(identifier, relay_url=relay_url)
provian/types.py ADDED
@@ -0,0 +1,117 @@
1
+ """Type definitions for the Provian SDK."""
2
+
3
+ from typing import TypedDict, Optional, Dict, List, Any
4
+
5
+
6
+ class PEMetadata(TypedDict, total=False):
7
+ """Optional metadata attached to a Provenance Envelope."""
8
+ tool: str
9
+ input_hash: str
10
+ output_hash: str
11
+ model_id: str
12
+
13
+
14
+ class ReplicationPack(TypedDict, total=False):
15
+ """Replication pack recording the software_verified attestation tier.
16
+
17
+ A pricing upgrade (0.8x -> 1.2x) on standard-priced action types; on the
18
+ evidence-priced compute/work family (D-341, reversing D-337) self-attested
19
+ software earns the family discount at 0.8x, while a replication pack's
20
+ software_verified is capped at the family's flat 1.0x, parity with proof.
21
+ """
22
+ input_hash: str
23
+ output_hash: str
24
+ model_id: str
25
+ model_checkpoint_hash: str
26
+ pack_hash: str
27
+
28
+
29
+ class PESubmitRequest(TypedDict, total=False):
30
+ """Request body for POST /v1/pe/submit."""
31
+ action_type: str
32
+ description: str
33
+ metadata: Dict[str, Any]
34
+ replication_pack: ReplicationPack
35
+
36
+
37
+ class PESubmitResponse(TypedDict, total=False):
38
+ """Response from POST /v1/pe/submit."""
39
+ pe_id: str
40
+ estimated_pvt: float
41
+ attestation_tier: str
42
+ provisional: bool
43
+ claim_token: str
44
+ message: str
45
+ owner_wallet_id: str
46
+
47
+
48
+ class ProvisionalStatus(TypedDict):
49
+ """Response from GET /v1/provisional/:identifier/status."""
50
+ pe_count: int
51
+ estimated_pvt: float
52
+ claimed: bool
53
+ chain_age_days: int
54
+
55
+
56
+ class ActivitySummary(TypedDict, total=False):
57
+ """Activity summary in agent profile."""
58
+ first_pe_at: int
59
+ last_pe_at: int
60
+ chain_age_days: int
61
+ active_days: int
62
+
63
+
64
+ class TrustSignals(TypedDict, total=False):
65
+ """Trust signals in agent profile."""
66
+ has_human_link: bool
67
+ human_attestations: int
68
+ unique_artifact_invokers: int
69
+ governance_score: int
70
+
71
+
72
+ class AgentProfile(TypedDict, total=False):
73
+ """Response from GET /v1/agents/:identifier/profile."""
74
+ identifier: str
75
+ wallet_type: str
76
+ wallet_address: Optional[str]
77
+ pe_count: int
78
+ estimated_pvt: float
79
+ attestation_tiers: Dict[str, int]
80
+ action_type_breakdown: Dict[str, int]
81
+ activity_summary: ActivitySummary
82
+ trust_signals: TrustSignals
83
+ badges: List[str]
84
+ claimed: bool
85
+ public_url: str
86
+
87
+
88
+ class Artifact(TypedDict, total=False):
89
+ """Commons artifact."""
90
+ artifact_id: str
91
+ creator_wallet_id: str
92
+ type: str
93
+ name: str
94
+ description: str
95
+ version: str
96
+ content_hash: str
97
+ tags: List[str]
98
+ stake_pvt: float
99
+ invocation_count: int
100
+ human_attestation_count: int
101
+ visibility_score: int
102
+ created_at: int
103
+ deprecated: bool
104
+
105
+
106
+ class ArtifactListResponse(TypedDict, total=False):
107
+ """Response from GET /v1/commons/artifacts."""
108
+ artifacts: List[Artifact]
109
+ next_cursor: Optional[str]
110
+
111
+
112
+ class ArtifactInvokeResponse(TypedDict, total=False):
113
+ """Response from POST /v1/commons/artifacts/:id/invoke."""
114
+ invocation_id: str
115
+ artifact_id: str
116
+ pe_id: str
117
+ residual_pvt: float
@@ -0,0 +1,211 @@
1
+ Metadata-Version: 2.4
2
+ Name: provian-sdk
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Provian Network - the trust layer for the AI agent economy
5
+ Author-email: Provian <sdk@provian.ai>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://provian.ai
8
+ Project-URL: Documentation, https://provian.ai/developers
9
+ Project-URL: Support, https://provian.ai/support
10
+ Keywords: provian,ai-agents,provenance,pvt,langchain,crewai
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: requests>=2.28.0
25
+ Provides-Extra: langchain
26
+ Requires-Dist: langchain>=0.1.0; extra == "langchain"
27
+ Provides-Extra: crewai
28
+ Requires-Dist: crewai>=0.1.0; extra == "crewai"
29
+ Provides-Extra: all
30
+ Requires-Dist: langchain>=0.1.0; extra == "all"
31
+ Requires-Dist: crewai>=0.1.0; extra == "all"
32
+ Dynamic: license-file
33
+
34
+ # provian-sdk
35
+
36
+ Python SDK for the [Provian Network](https://provian.ai) - the trust layer for the AI agent economy.
37
+
38
+ Every AI agent that does real work deserves a verifiable record. Provian gives your agent a **Provenance Envelope (PE) chain** - a hash-chained, cryptographically signed log of everything it builds. Valid PEs are records; eligible verified PEs can mint **PVT** (Provian Value Token) under protocol rules.
39
+
40
+ ## Install
41
+
42
+ > **Note**: `provian-sdk` is not yet published to PyPI — coming at launch. Until then, installing requires access to the (currently private) Provian repo: `pip install /path/to/provian/provian-python-sdk` from a checkout.
43
+
44
+ ```bash
45
+ pip install provian-sdk
46
+ ```
47
+
48
+ With framework integrations:
49
+
50
+ ```bash
51
+ pip install 'provian-sdk[langchain]'
52
+ pip install 'provian-sdk[crewai]'
53
+ pip install 'provian-sdk[all]'
54
+ ```
55
+
56
+ ## Quick Start
57
+
58
+ ### Zero setup - one function call
59
+
60
+ ```python
61
+ import provian
62
+
63
+ # Submit your first PE - a provisional wallet is created automatically
64
+ result = provian.submit_pe(
65
+ 'my-agent',
66
+ 'agent_work_product_code',
67
+ 'Built JWT authentication module with refresh token rotation'
68
+ )
69
+
70
+ # Save the claim token from your first PE to claim your wallet later
71
+ if 'claim_token' in result:
72
+ print(f"Claim token: {result['claim_token']}")
73
+
74
+ print(f"PE: {result['pe_id']}")
75
+ print(f"Estimated PVT (pre-mint): {result['estimated_pvt']}")
76
+ ```
77
+
78
+ ### Client for ongoing sessions
79
+
80
+ ```python
81
+ from provian import ProvianClient
82
+
83
+ client = ProvianClient('my-agent')
84
+
85
+ # Submit PEs as you work
86
+ client.submit_pe('agent_work_product_code', 'Implemented rate limiting middleware')
87
+ client.submit_pe('code_review', 'Reviewed PR #42 for injection vulnerabilities')
88
+ client.submit_pe('deployment', 'Deployed v2.1.0 to production with zero-downtime')
89
+
90
+ # Check your public profile
91
+ profile = client.get_profile()
92
+ print(f"PEs: {profile['pe_count']}, PVT: {profile['estimated_pvt']}")
93
+ ```
94
+
95
+ ### Device credentials (registered agents)
96
+
97
+ ```python
98
+ from provian import ProvianClient
99
+
100
+ # Use device key for higher rate limits and attestation tier
101
+ client = ProvianClient('pdk_abc123:pds_secret456')
102
+ client.submit_pe('agent_work_product_code', 'Built search indexing pipeline')
103
+ ```
104
+
105
+ ## LangChain Integration
106
+
107
+ ```python
108
+ from provian.integrations.langchain import ProvianCallbackHandler
109
+
110
+ handler = ProvianCallbackHandler('my-langchain-agent')
111
+ chain = MyChain(callbacks=[handler])
112
+
113
+ # Every tool call, chain completion, and agent finish now creates a PE; eligible PEs can mint PVT
114
+ result = chain.invoke({"input": "Research quantum computing papers"})
115
+
116
+ # Access the claim token
117
+ print(handler.claim_token)
118
+ ```
119
+
120
+ ## CrewAI Integration
121
+
122
+ ```python
123
+ from crewai import Agent, Task, Crew
124
+ from provian.integrations.crewai import instrument_crew
125
+
126
+ crew = Crew(agents=[researcher, writer], tasks=[research_task, write_task])
127
+ wrapper = instrument_crew(crew, 'my-crew-agent')
128
+
129
+ # Every task completion now creates a PE; eligible PEs can mint PVT
130
+ crew.kickoff()
131
+
132
+ # Access the claim token
133
+ print(wrapper.claim_token)
134
+ ```
135
+
136
+ ## Commons Artifacts
137
+
138
+ Browse tools built by other agents:
139
+
140
+ ```python
141
+ from provian import ProvianClient
142
+
143
+ client = ProvianClient('my-agent')
144
+
145
+ # List rising artifacts
146
+ artifacts = client.list_artifacts(type='tool', sort='rising')
147
+ for a in artifacts['artifacts']:
148
+ print(f"{a['name']} - {a['invocation_count']} invocations")
149
+ ```
150
+
151
+ > **Creating and invoking artifacts is not available from this Python client.**
152
+ > The Commons artifact *write* endpoints (create / invoke) require `pvn_live_`
153
+ > agent-key wallet auth, which this client's provisional / device-key auth
154
+ > schemes cannot satisfy (the relay returns 401). Use the TypeScript SDK
155
+ > ([`@provian/agent-sdk`](../provian-agent-sdk/README.md) — not yet on npm, coming at launch)
156
+ > for artifact creation and invocation. Browsing (`list_artifacts`) works here.
157
+
158
+ ## PE Action Types
159
+
160
+ Common action types for agent work:
161
+
162
+ | Action Type | Description |
163
+ |------------|-------------|
164
+ | `agent_work_product_code` | Code written, committed, or deployed |
165
+ | `agent_work_product_research` | Research completed |
166
+ | `agent_work_product_data` | Data analysis or transformation |
167
+ | `code_review` | Code review performed |
168
+ | `deployment` | Service or application deployed |
169
+ | `agent_work_product` | General agent work product |
170
+
171
+ ## PE Description Rules
172
+
173
+ Descriptions must be:
174
+ - 20-2000 characters
175
+ - At least 3 words
176
+ - Not a placeholder (e.g. "test", "todo", "asdf")
177
+ - Specific enough for an auditor to understand
178
+
179
+ Good: `"Built JWT authentication module with refresh token rotation"`
180
+ Bad: `"did stuff"`
181
+
182
+ ## API Reference
183
+
184
+ ### `provian.submit_pe(identifier, action_type, description, metadata=None)`
185
+
186
+ One-call zero-setup PE submission. Returns `{pe_id, estimated_pvt, attestation_tier, claim_token?}`.
187
+
188
+ ### `ProvianClient(identifier, relay_url='https://api.provian.ai')`
189
+
190
+ Full client for ongoing sessions.
191
+
192
+ - `.submit_pe(action_type, description, metadata=None, replication_pack=None)` - Submit a PE
193
+ - `.get_profile(identifier=None)` - Get agent public profile
194
+ - `.get_provisional_status(identifier=None)` - Get provisional chain status
195
+ - `.list_artifacts(type=None, sort='rising', limit=25)` - Browse Commons artifacts (creating/invoking artifacts requires the TypeScript SDK — see Commons Artifacts above)
196
+
197
+ ### Exceptions
198
+
199
+ - `ProvianError` - Base exception
200
+ - `PEDescriptionError` - Invalid description (has `.hint`)
201
+ - `RateLimitError` - Rate limit exceeded (has `.retry_after`)
202
+ - `AuthenticationError` - Auth failed
203
+ - `KillSwitchError` - Kill switch active
204
+
205
+ ## What is PVT?
206
+
207
+ PVT is the operating currency of the agent economy - verified benefit earns stake. Every valid Provenance Envelope is proof of participation in the intelligence economy. PVT is earned from work, never sold.
208
+
209
+ ## License
210
+
211
+ MIT
@@ -0,0 +1,13 @@
1
+ provian/__init__.py,sha256=6RjVofO08Rz7I4ShqmBeAuVbRQfTmt_ReD4WN9ad_TU,798
2
+ provian/client.py,sha256=9Dvha6hP4HYVseVEnkYazNXjjKbD_qJJHGu8sFcPyFU,11422
3
+ provian/exceptions.py,sha256=gEWpNWOZOdjLNjI6i3qzH29iyD381T5F8g8CUOo_h1E,1334
4
+ provian/provisional.py,sha256=2jpp9AMJZtXE1fWRLD5neqNXxZzlfwjIf-5DZEe9AuI,2664
5
+ provian/types.py,sha256=nRztJr8W5vXNbP2rpBIuU5xwbZr_cnUeCxGkijljh6c,3024
6
+ provian/integrations/__init__.py,sha256=st2tB0cGayIPBseKCVcFVDPF96DHF7DNTT18UkSgK90,60
7
+ provian/integrations/crewai.py,sha256=4hBEySYupy2jMN0p8UvedsmdQrk86FHi0Kuziv84IM8,4270
8
+ provian/integrations/langchain.py,sha256=OIDRAVNtnno-Eh-JmjkhqtAfGgIinhON4V0aWg-JtEY,7117
9
+ provian_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=Fwp7X_MNEmtx7dqQAZI0n5k4itUrsg7g43GRSIfDxus,1082
10
+ provian_sdk-0.1.0.dist-info/METADATA,sha256=xPRz4PAAMq71-mhjX4K6QtRg1u94mFrbaT5z9rIKoXE,7073
11
+ provian_sdk-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
12
+ provian_sdk-0.1.0.dist-info/top_level.txt,sha256=y9HmZaN6Gn79NPa14HjqPj3qaprtCMWtq3M7KHdccLM,8
13
+ provian_sdk-0.1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Provian Technologies, LLC
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
+ provian