Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
python client
Antonio Ojead5ed691a551e
diff --git a/python/README.md b/python/README.mdindex b14b5c98..246a1a99 100644--- a/python/README.md+++ b/python/README.md@@ -1,22 +1,187 @@-# SAM Python Client (Preview)+# SAM Python Client Framework-This package provides Python artifacts for the SAM sovereign auth flow:+This package provides an idiomatic async Python client for the SAM (Sovereign Agent Mesh):-- Protocol IDs: `/sam/auth/1.0.0`, `/sam/a2a/1.0.0`, `/sam/mcp/1.0.0`-- Passport biscuit validation (Hub-signed Ed25519 envelope)-- Application-layer auth handshake helpers-- Local reputation trust cache backed by SQLite+## Features-## Install+- **MeshClient**: High-level async API for mesh operations+- **OIDC Device Flow**: Hub authentication with device authorization grant+- **Passport Management**: Hub-issued biscuit validation and credential persistence+- **Protocol Support**: `/sam/auth/1.0.0`, `/sam/a2a/1.0.0`, `/sam/mcp/1.0.0`+- **Credential Store**: SQLite-backed local identity storage (~/.config/sam/state.db)+- **Trust Cache**: Peer reputation tracking and scoring++## Quick Start++### Installation```bashcd pythonpython -m pip install -e .```+### Authentication++```python+import asyncio+from sam_mesh import MeshClient++async def main():+ async with MeshClient("https://hub.example.com") as client:+ # Authenticate via OIDC device flow+ creds = await client.login()+ print(f"Logged in as {creds.peer_id}")++ # Credentials are automatically saved to ~/.config/sam/state.db++if __name__ == "__main__":+ asyncio.run(main())+```++### Loading Existing Credentials++```python+from sam_mesh import MeshClient++client = MeshClient("https://hub.example.com")+creds = client.load_credentials()+if creds:+ print(f"Using existing identity: {creds.peer_id}")+```++### Validating Passports++```python+from sam_mesh import MeshClient, validate_passport_biscuit++client = MeshClient("https://hub.example.com")+creds = client.load_credentials()++# Validate a passport biscuit received from a peer+claims = client.validate_passport(+ biscuit=creds.passport_biscuit,+ hub_public_key_b64="...",+ expected_peer_id=creds.peer_id,+)+print(f"Validated: {claims.subject}")+```++## API Reference++### MeshClient++High-level async client for SAM operations.++```python+client = MeshClient(+ hub_url: str,+ credential_store: Optional[CredentialStore] = None,+ client_id: str = "sam-cli",+)+```++**Methods:**++- `async login() -> StoredCredentials`: Authenticate via OIDC device flow+- `load_credentials() -> Optional[StoredCredentials]`: Load stored identity+- `validate_passport(...) -> PassportClaims`: Validate a biscuit+- `async fetch_hub_p2p_info() -> dict`: Get hub's P2P bootstrap addresses+- `close()`: Release resources++### HubClient++Low-level client for hub HTTP operations.++```python+async with HubClient(hub_url, client_id="my-app") as hub:+ # OIDC discovery+ discovery = await hub.discover()++ # Device flow+ auth = await hub.start_device_flow(discovery.device_authorization_endpoint)+ token = await hub.poll_device_token(discovery.token_endpoint, auth)++ # Passport issuance+ biscuit = await hub.issue_passport_biscuit(+ access_token=token.access_token,+ peer_id="...",+ federation_id="default",+ )++ # P2P bootstrap info+ info = await hub.fetch_p2p_info()+ peer_id, addrs = info["peer_id"], info["addrs"]+```++### CredentialStore++Manages persistent local credentials.++```python+from sam_mesh import CredentialStore, default_credential_store++# Use default location+store = default_credential_store()++# Or specify a path+store = CredentialStore("/path/to/state.db")++# Load credentials+creds = store.load()++# Save credentials+store.save(creds)++# Clean up+store.close()+```++### PassportClaims++Validated passport biscuit claims.++```python+from dataclasses import dataclass+from datetime import datetime++@dataclass+class PassportClaims:+ token: str+ issuer: str+ peer_id: str+ mesh_id: str+ subject: str+ claims: dict[str, str]+ issued_at: datetime | None+```++## Exception Hierarchy++All exceptions inherit from `SAMError`:++- `SAMError`: Base exception+- `AuthenticationError`: Auth protocol failures+- `CredentialError`: Credential store issues+- `HubError`: Hub communication failures+- `ValidationError`: Passport validation failures+- `TimeoutError`: Operation timeouts+- `ConnectionError`: Peer connection failures++## Design++The client follows Python async best practices:++- **Async-first**: All I/O operations use `async/await`+- **Context managers**: Proper resource cleanup with `async with`+- **Type hints**: Full type annotations for IDE support+- **Structured exceptions**: Clear error handling+- **Idiomatic**: Follows Python conventions and style (PEP 8)+## Notes-- Transport compliance (TLS 1.3-only, QUIC first, TCP+TLS fallback) must be- configured in the py-libp2p host builder for your runtime.+- Requires Python 3.10++- libp2p host configuration (TLS 1.3, QUIC, TCP) must be set up separately+- Hub must support OIDC discovery and device authorization grant+- This library focuses on identity/auth hook and trust cache parity with Go.- Default relay/rendezvous host hint is `app.sam-mesh.dev`.diff --git a/python/examples/libp2p_integration.py b/python/examples/libp2p_integration.pynew file mode 100644index 00000000..4dc982ed--- /dev/null+++ b/python/examples/libp2p_integration.py@@ -0,0 +1,62 @@+#!/usr/bin/env python3+"""Example: Integrate SAM client with libp2p host and authenticate peers."""++import asyncio+from typing import Any++from sam_mesh import MeshClient, authenticate_peer, validate_passport_biscuit+++async def example_with_libp2p_host():+ """+ Example showing how to integrate SAM auth with a libp2p host.++ In real usage:+ 1. Create a libp2p host (using py-libp2p)+ 2. Load or authenticate with the SAM hub to get a passport+ 3. Set up stream handlers for /sam/auth/1.0.0 and other SAM protocols+ 4. Call authenticate_peer when connecting to other agents+ """++ # Load credentials+ client = MeshClient("https://hub.example.com")+ creds = client.load_credentials()++ if not creds:+ print("No credentials found. Run login.py first.")+ return++ print(f"Using peer ID: {creds.peer_id}")+ print(f"Passport biscuit: {creds.passport_biscuit[:50]}...")++ # In a real scenario, you would:++ # 1. Create a libp2p host+ # host = await create_libp2p_host(...)++ # 2. Register the SAM auth protocol handler+ # host.set_stream_handler("/sam/auth/1.0.0", handle_auth_stream)++ # 3. When connecting to a peer, authenticate them+ # await authenticate_peer(+ # open_stream=host.new_stream,+ # peer_id=remote_peer_id,+ # local_passport=creds.passport_biscuit,+ # hub_public_key_b64="...", # from hub+ # mesh_id="default",+ # )++ # 4. Validate their passport+ # claims = validate_passport_biscuit(+ # their_passport,+ # hub_public_key_b64="...",+ # expected_peer_id=remote_peer_id,+ # expected_mesh_id="default",+ # )+ # print(f"Authenticated peer: {claims.subject}")++ print("\nExample structure shown above. See auth.py for protocol details.")+++if __name__ == "__main__":+ asyncio.run(example_with_libp2p_host())diff --git a/python/examples/load_credentials.py b/python/examples/load_credentials.pynew file mode 100644index 00000000..02a46ba3--- /dev/null+++ b/python/examples/load_credentials.py@@ -0,0 +1,36 @@+#!/usr/bin/env python3+"""Example: Load stored credentials and validate a passport."""++import sys++from sam_mesh import MeshClient, ValidationError+++def main():+ """Load and display stored credentials."""+ client = MeshClient("https://hub.example.com")++ try:+ creds = client.load_credentials()++ if not creds:+ print("No stored credentials found. Run login.py first.", file=sys.stderr)+ sys.exit(1)++ print(f"Peer ID: {creds.peer_id}", file=sys.stderr)+ print(f"Hub URL: {creds.hub_url}", file=sys.stderr)+ print(f"Passport Biscuit: {creds.passport_biscuit[:50]}...", file=sys.stderr)++ if creds.token_expiry:+ print(f"Token expires at: {creds.token_expiry}", file=sys.stderr)++ print("\nTo use credentials in a mesh node, pass the passport biscuit:", file=sys.stderr)+ print(f" passport = '{creds.passport_biscuit}'", file=sys.stderr)++ except Exception as e:+ print(f"Error: {e}", file=sys.stderr)+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/python/examples/login.py b/python/examples/login.pynew file mode 100644index 00000000..33095781--- /dev/null+++ b/python/examples/login.py@@ -0,0 +1,33 @@+#!/usr/bin/env python3+"""Example: Authenticate with a SAM Hub via OIDC device flow."""++import asyncio+import sys++from sam_mesh import MeshClient+++async def main():+ """Authenticate and save credentials to ~/.config/sam/state.db."""+ hub_url = "https://hub.example.com"+ if len(sys.argv) > 1:+ hub_url = sys.argv[1]++ print(f"Authenticating with hub: {hub_url}\n", file=sys.stderr)++ async with MeshClient(hub_url) as client:+ try:+ # Start OIDC device flow — this will prompt the user to visit a URL+ # and enter a code in the browser+ creds = await client.login()++ print(f"✓ Successfully authenticated as peer {creds.peer_id}", file=sys.stderr)+ print(f"✓ Hub: {creds.hub_url}", file=sys.stderr)+ print(f"✓ Passport biscuit issued", file=sys.stderr)+ except Exception as e:+ print(f"✗ Authentication failed: {e}", file=sys.stderr)+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/python/pyproject.toml b/python/pyproject.tomlindex 44e29a9f..7588c91f 100644--- a/python/pyproject.toml+++ b/python/pyproject.toml@@ -5,14 +5,23 @@ build-backend = "setuptools.build_meta"[project]name = "sam-mesh-client"version = "0.1.0"-description = "Python client artifacts for SAM (Sovereign Agent Mesh)"+description = "Python client framework for SAM (Sovereign Agent Mesh)"readme = "README.md"requires-python = ">=3.10"authors = [{ name = "SAM Contributors" }]dependencies = [+ "httpx>=0.24.0","pynacl>=1.5.0",]+[project.optional-dependencies]+dev = [+ "pytest>=7.0",+ "pytest-asyncio>=0.21.0",+ "black>=23.0",+ "ruff>=0.1.0",+]+[tool.setuptools.packages.find]where = ["."]include = ["sam_mesh*"]diff --git a/python/sam_mesh/__init__.py b/python/sam_mesh/__init__.pyindex d9859546..82be1aab 100644--- a/python/sam_mesh/__init__.py+++ b/python/sam_mesh/__init__.py@@ -1,23 +1,59 @@+"""SAM Mesh — Python client for the Sovereign Agent Mesh."""+from .auth import (+ A2A_PROTOCOL_ID,+ AUTH_PROTOCOL_ID,DEFAULT_HUB_ISSUER,DEFAULT_RELAY_RENDEZVOUS,- AUTH_PROTOCOL_ID,- A2A_PROTOCOL_ID,MCP_PROTOCOL_ID,PassportClaims,- validate_passport_biscuit,authenticate_peer,+ validate_passport_biscuit,+)+from .client import MeshClient+from .credentials import CredentialStore, StoredCredentials, default_credential_store+from .exceptions import (+ AuthenticationError,+ ConnectionError,+ CredentialError,+ HubError,+ SAMError,+ TimeoutError,+ ValidationError,)+from .hub import HubClientfrom .trust_cache import SQLiteTrustCache+__version__ = "0.1.0"+__all__ = [- "DEFAULT_HUB_ISSUER",- "DEFAULT_RELAY_RENDEZVOUS",- "AUTH_PROTOCOL_ID",- "A2A_PROTOCOL_ID",- "MCP_PROTOCOL_ID",+ # High-level client+ "MeshClient",+ # Hub and auth+ "HubClient",+ # Credentials+ "CredentialStore",+ "StoredCredentials",+ "default_credential_store",+ # Passport validation"PassportClaims","validate_passport_biscuit","authenticate_peer",+ # Protocol IDs+ "AUTH_PROTOCOL_ID",+ "A2A_PROTOCOL_ID",+ "MCP_PROTOCOL_ID",+ # Constants+ "DEFAULT_HUB_ISSUER",+ "DEFAULT_RELAY_RENDEZVOUS",+ # Exceptions+ "SAMError",+ "AuthenticationError",+ "CredentialError",+ "HubError",+ "ValidationError",+ "TimeoutError",+ "ConnectionError",+ # Trust cache"SQLiteTrustCache",]diff --git a/python/sam_mesh/__pycache__/__init__.cpython-312.pyc b/python/sam_mesh/__pycache__/__init__.cpython-312.pycnew file mode 100644index 00000000..7158f19cBinary files /dev/null and b/python/sam_mesh/__pycache__/__init__.cpython-312.pyc differdiff --git a/python/sam_mesh/__pycache__/auth.cpython-312.pyc b/python/sam_mesh/__pycache__/auth.cpython-312.pycnew file mode 100644index 00000000..56b105cfBinary files /dev/null and b/python/sam_mesh/__pycache__/auth.cpython-312.pyc differdiff --git a/python/sam_mesh/__pycache__/client.cpython-312.pyc b/python/sam_mesh/__pycache__/client.cpython-312.pycnew file mode 100644index 00000000..f396f9e3Binary files /dev/null and b/python/sam_mesh/__pycache__/client.cpython-312.pyc differdiff --git a/python/sam_mesh/__pycache__/credentials.cpython-312.pyc b/python/sam_mesh/__pycache__/credentials.cpython-312.pycnew file mode 100644index 00000000..82342f14Binary files /dev/null and b/python/sam_mesh/__pycache__/credentials.cpython-312.pyc differdiff --git a/python/sam_mesh/__pycache__/exceptions.cpython-312.pyc b/python/sam_mesh/__pycache__/exceptions.cpython-312.pycnew file mode 100644index 00000000..8233b996Binary files /dev/null and b/python/sam_mesh/__pycache__/exceptions.cpython-312.pyc differdiff --git a/python/sam_mesh/__pycache__/hub.cpython-312.pyc b/python/sam_mesh/__pycache__/hub.cpython-312.pycnew file mode 100644index 00000000..7fb57f2dBinary files /dev/null and b/python/sam_mesh/__pycache__/hub.cpython-312.pyc differdiff --git a/python/sam_mesh/__pycache__/trust_cache.cpython-312.pyc b/python/sam_mesh/__pycache__/trust_cache.cpython-312.pycnew file mode 100644index 00000000..40591197Binary files /dev/null and b/python/sam_mesh/__pycache__/trust_cache.cpython-312.pyc differdiff --git a/python/sam_mesh/client.py b/python/sam_mesh/client.pynew file mode 100644index 00000000..7ef9cc36--- /dev/null+++ b/python/sam_mesh/client.py@@ -0,0 +1,232 @@+"""High-level SAM mesh client for Python."""++from __future__ import annotations++import sys+from typing import Optional++from .auth import PassportClaims, validate_passport_biscuit+from .credentials import CredentialStore, StoredCredentials, default_credential_store+from .exceptions import (+ AuthenticationError,+ CredentialError,+ HubError,+ SAMError,+ ValidationError,+)+from .hub import HubClient+++class MeshClient:+ """+ Idiomatic async Python client for the SAM sovereign mesh.++ Provides:+ - OIDC device flow authentication+ - Hub-issued passport biscuit management+ - Credential persistence+ - Peer authentication and validation+ """++ def __init__(+ self,+ hub_url: str,+ *,+ credential_store: Optional[CredentialStore] = None,+ client_id: str = "sam-cli",+ ):+ """+ Initialize the mesh client.++ Args:+ hub_url: Base URL of the SAM Hub.+ credential_store: Credential store (uses default ~/.config/sam/state.db if None).+ client_id: OAuth2 client ID (default: "sam-cli").+ """+ self.hub_url = hub_url+ self.client_id = client_id+ self._cred_store = credential_store+ self._owned_store = credential_store is None+ self._hub_client: Optional[HubClient] = None+ self._local_creds: Optional[StoredCredentials] = None++ def __enter__(self) -> MeshClient:+ """Context manager entry."""+ if self._owned_store and self._cred_store is None:+ self._cred_store = default_credential_store()+ return self++ def __exit__(self, exc_type, exc_val, exc_tb) -> None:+ """Context manager exit."""+ self.close()++ async def __aenter__(self) -> MeshClient:+ """Async context manager entry."""+ self.__enter__()+ return self++ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:+ """Async context manager exit."""+ self.close()++ def close(self) -> None:+ """Close the client and release resources."""+ if self._cred_store and self._owned_store:+ self._cred_store.close()++ def _ensure_store(self) -> CredentialStore:+ """Ensure credential store is initialized."""+ if self._cred_store is None:+ self._cred_store = default_credential_store()+ self._owned_store = True+ return self._cred_store++ def load_credentials(self) -> Optional[StoredCredentials]:+ """+ Load stored credentials from the local store.++ Returns:+ StoredCredentials or None if no identity exists.+ """+ try:+ store = self._ensure_store()+ return store.load()+ except Exception as e:+ raise CredentialError(f"failed to load credentials: {e}") from e++ async def login(self) -> StoredCredentials:+ """+ Authenticate via the hub using OIDC device authorization grant flow.++ Prompts the user to visit a URL and enter a code. Returns once the user+ completes sign-in and the hub issues a passport biscuit.++ Returns:+ StoredCredentials with access token and passport biscuit.++ Raises:+ HubError: If authentication fails.+ CredentialError: If credential storage fails.+ """+ try:+ async with HubClient(self.hub_url, client_id=self.client_id) as hub:+ # Discover OIDC endpoints+ discovery = await hub.discover()++ # Start device flow+ auth = await hub.start_device_flow(discovery.device_authorization_endpoint)++ # Display codes to user+ verify_url = auth.verification_uri_complete or auth.verification_uri+ print(f"\nOpen this URL in your browser:\n\n {verify_url}\n", file=sys.stderr)+ if not auth.verification_uri_complete:+ print(f"And enter code: {auth.user_code}\n", file=sys.stderr)+ print(f"Waiting for authorization (expires in {auth.expires_in}s) …\n", file=sys.stderr)++ # Poll for token+ token_result = await hub.poll_device_token(+ discovery.token_endpoint,+ auth,+ max_wait_secs=float(auth.expires_in),+ )++ # For now, use a placeholder peer ID. In practice, this would come+ # from the libp2p host after it's created.+ # The real flow in Go: build node -> get peer ID -> issue passport+ print("Authorization successful. Issuing passport …\n", file=sys.stderr)++ # TODO: this should come from the libp2p host's PeerID()+ # For now we'll issue without a peer ID and update after node is built+ peer_id = "temp-placeholder"+ biscuit = await hub.issue_passport_biscuit(+ token_result.access_token,+ peer_id=peer_id,+ federation_id="default",+ subject=peer_id,+ )++ # Store credentials+ creds = StoredCredentials(+ peer_id=peer_id,+ hub_url=self.hub_url,+ access_token=token_result.access_token,+ refresh_token=token_result.refresh_token or "",+ passport_biscuit=biscuit,+ )+ store = self._ensure_store()+ store.save(creds)+ self._local_creds = creds++ print(f"Logged in as peer {peer_id}\n", file=sys.stderr)+ print(f"Credentials saved to {store._path}\n", file=sys.stderr)++ return creds+ except HubError:+ raise+ except Exception as e:+ raise HubError(f"authentication failed: {e}") from e++ def validate_passport(+ self,+ biscuit: str,+ *,+ hub_public_key_b64: str,+ expected_peer_id: str,+ expected_mesh_id: str = "default",+ ) -> PassportClaims:+ """+ Validate a passport biscuit.++ Args:+ biscuit: The passport biscuit token.+ hub_public_key_b64: Hub's Ed25519 public key (base64-encoded).+ expected_peer_id: Expected peer ID in the biscuit.+ expected_mesh_id: Expected federation/mesh ID.++ Returns:+ PassportClaims with validated claims.++ Raises:+ ValidationError: If the biscuit is invalid.+ """+ try:+ return validate_passport_biscuit(+ biscuit,+ hub_public_key_b64=hub_public_key_b64,+ expected_peer_id=expected_peer_id,+ expected_mesh_id=expected_mesh_id,+ )+ except ValueError as e:+ raise ValidationError(f"passport validation failed: {e}") from e++ async def fetch_hub_p2p_info(self) -> dict:+ """+ Fetch the hub's P2P bootstrap information.++ Returns:+ Dict with 'peer_id' and 'addrs' keys.++ Raises:+ HubError: If the hub is not running in P2P mode.+ """+ try:+ async with HubClient(self.hub_url) as hub:+ return await hub.fetch_p2p_info()+ except HubError:+ raise+ except Exception as e:+ raise HubError(f"failed to fetch hub P2P info: {e}") from e+++__all__ = [+ "MeshClient",+ "HubClient",+ "CredentialStore",+ "StoredCredentials",+ "PassportClaims",+ "SAMError",+ "AuthenticationError",+ "CredentialError",+ "HubError",+ "ValidationError",+]diff --git a/python/sam_mesh/credentials.py b/python/sam_mesh/credentials.pynew file mode 100644index 00000000..71ca0a36--- /dev/null+++ b/python/sam_mesh/credentials.py@@ -0,0 +1,168 @@+"""Local credential store for SAM identities."""++from __future__ import annotations++import json+import sqlite3+from dataclasses import asdict, dataclass, field+from datetime import datetime+from pathlib import Path+from typing import Optional++from .exceptions import CredentialError+++@dataclass+class StoredCredentials:+ """Persisted identity state in the SAM credential store."""++ peer_id: str+ """Local libp2p peer ID."""++ hub_url: str+ """Hub the user authenticated against."""++ access_token: str+ """OAuth2 access token returned by the Hub."""++ passport_biscuit: str+ """Hub-issued biscuit binding identity to peer/federation."""++ refresh_token: str = ""+ """Refresh token for silent token renewal."""++ token_expiry: Optional[datetime] = None+ """When the access token expires."""++ def to_dict(self) -> dict:+ """Serialize to dict for JSON storage."""+ data = asdict(self)+ if self.token_expiry:+ data["token_expiry"] = self.token_expiry.isoformat()+ return data++ @classmethod+ def from_dict(cls, data: dict) -> StoredCredentials:+ """Deserialize from dict."""+ if "token_expiry" in data and data["token_expiry"]:+ try:+ data["token_expiry"] = datetime.fromisoformat(+ data["token_expiry"].replace("Z", "+00:00")+ )+ except (ValueError, TypeError):+ data["token_expiry"] = None+ return cls(**data)+++class CredentialStore:+ """Reads and writes SAM credentials from a local SQLite store."""++ def __init__(self, db_path: str | Path):+ """+ Initialize the credential store.++ Args:+ db_path: Path to SQLite database file.+ """+ self._path = str(db_path)+ self._conn = sqlite3.connect(self._path)+ self._init_schema()++ def _init_schema(self) -> None:+ """Create tables if they don't exist."""+ self._conn.execute(+ """+ CREATE TABLE IF NOT EXISTS credentials (+ key TEXT PRIMARY KEY,+ data TEXT NOT NULL+ )+ """+ )+ self._conn.commit()++ def load(self) -> Optional[StoredCredentials]:+ """+ Load stored credentials. Returns None if no identity exists.++ Returns:+ StoredCredentials or None.++ Raises:+ CredentialError: If load fails.+ """+ try:+ row = self._conn.execute(+ "SELECT data FROM credentials WHERE key = 'local'"+ ).fetchone()+ if not row:+ return None+ data = json.loads(row[0])+ return StoredCredentials.from_dict(data)+ except Exception as e:+ raise CredentialError(f"failed to load credentials: {e}") from e++ def save(self, creds: StoredCredentials) -> None:+ """+ Save credentials to the store.++ Args:+ creds: Credentials to save.++ Raises:+ CredentialError: If save fails.+ """+ try:+ data = json.dumps(creds.to_dict())+ self._conn.execute(+ """+ INSERT INTO credentials(key, data)+ VALUES ('local', ?)+ ON CONFLICT(key) DO UPDATE SET data = excluded.data+ """,+ (data,),+ )+ self._conn.commit()+ except Exception as e:+ raise CredentialError(f"failed to save credentials: {e}") from e++ def delete(self) -> None:+ """Delete stored credentials."""+ try:+ self._conn.execute("DELETE FROM credentials WHERE key = 'local'")+ self._conn.commit()+ except Exception as e:+ raise CredentialError(f"failed to delete credentials: {e}") from e++ def close(self) -> None:+ """Close the credential store."""+ if self._conn:+ self._conn.close()++ def __enter__(self) -> CredentialStore:+ """Context manager entry."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb) -> None:+ """Context manager exit."""+ self.close()+++def default_credential_store() -> CredentialStore:+ """+ Return a credential store using the default SAM state directory.++ The default path is ~/.config/sam/state.db.++ Returns:+ CredentialStore instance.++ Raises:+ CredentialError: If the default path cannot be resolved.+ """+ try:+ config_dir = Path.home() / ".config" / "sam"+ config_dir.mkdir(parents=True, exist_ok=True)+ db_path = config_dir / "state.db"+ return CredentialStore(str(db_path))+ except Exception as e:+ raise CredentialError(f"failed to initialize default credential store: {e}") from ediff --git a/python/sam_mesh/exceptions.py b/python/sam_mesh/exceptions.pynew file mode 100644index 00000000..4851183a--- /dev/null+++ b/python/sam_mesh/exceptions.py@@ -0,0 +1,43 @@+"""SAM client exceptions."""+++class SAMError(Exception):+ """Base exception for all SAM client errors."""++ pass+++class AuthenticationError(SAMError):+ """Raised when passport authentication fails."""++ pass+++class HubError(SAMError):+ """Raised when hub communication or OIDC flow fails."""++ pass+++class CredentialError(SAMError):+ """Raised when credential store operations fail."""++ pass+++class ValidationError(SAMError):+ """Raised when passport or message validation fails."""++ pass+++class TimeoutError(SAMError):+ """Raised when an operation times out."""++ pass+++class ConnectionError(SAMError):+ """Raised when a peer connection fails."""++ passdiff --git a/python/sam_mesh/hub.py b/python/sam_mesh/hub.pynew file mode 100644index 00000000..4ad60b9a--- /dev/null+++ b/python/sam_mesh/hub.py@@ -0,0 +1,277 @@+"""SAM Hub client for OIDC authentication and passport issuance."""++from __future__ import annotations++import asyncio+import json+from dataclasses import dataclass+from typing import Optional++import httpx++from .exceptions import HubError, ValidationError+++@dataclass+class HubDiscovery:+ """OIDC discovery document from the hub."""++ issuer: str+ authorization_endpoint: str+ token_endpoint: str+ device_authorization_endpoint: str+ jwks_uri: str+++@dataclass+class DeviceFlowAuth:+ """Device authorization flow response."""++ device_code: str+ user_code: str+ verification_uri: str+ verification_uri_complete: str+ expires_in: int+ interval: int = 5+++@dataclass+class DeviceFlowToken:+ """Token response from device flow."""++ access_token: str+ refresh_token: Optional[str] = None+ expires_in: Optional[int] = None+++class HubClient:+ """Client for SAM Hub OIDC and passport operations."""++ def __init__(self, hub_url: str, client_id: str = "sam-cli", timeout: float = 30.0):+ """+ Initialize the hub client.++ Args:+ hub_url: Base URL of the SAM Hub (e.g. https://hub.example.com).+ client_id: OAuth2 client ID registered with the hub.+ timeout: Request timeout in seconds.+ """+ self.hub_url = hub_url.rstrip("/")+ self.client_id = client_id+ self.timeout = timeout+ self._http_client: Optional[httpx.AsyncClient] = None++ async def __aenter__(self) -> HubClient:+ """Async context manager entry."""+ self._http_client = httpx.AsyncClient(timeout=self.timeout)+ return self++ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:+ """Async context manager exit."""+ if self._http_client:+ await self._http_client.aclose()++ async def discover(self) -> HubDiscovery:+ """+ Fetch the hub's OIDC discovery document.++ Returns:+ HubDiscovery with endpoints.++ Raises:+ HubError: If discovery fails.+ """+ if not self._http_client:+ raise HubError("hub client not initialized (use async context manager)")++ try:+ url = f"{self.hub_url}/.well-known/openid-configuration"+ resp = await self._http_client.get(url)+ resp.raise_for_status()+ data = resp.json()++ return HubDiscovery(+ issuer=data.get("issuer", ""),+ authorization_endpoint=data.get("authorization_endpoint", ""),+ token_endpoint=data.get("token_endpoint", ""),+ device_authorization_endpoint=data.get("device_authorization_endpoint", ""),+ jwks_uri=data.get("jwks_uri", ""),+ )+ except httpx.HTTPError as e:+ raise HubError(f"hub discovery failed: {e}") from e++ async def start_device_flow(self, device_auth_endpoint: str) -> DeviceFlowAuth:+ """+ Start the OAuth2 device authorization grant flow.++ Args:+ device_auth_endpoint: Device authorization endpoint URL.++ Returns:+ DeviceFlowAuth with user code and verification URI.++ Raises:+ HubError: If the flow cannot be started.+ """+ if not self._http_client:+ raise HubError("hub client not initialized (use async context manager)")++ try:+ payload = {+ "client_id": self.client_id,+ "scope": "openid profile email",+ }+ resp = await self._http_client.post(device_auth_endpoint, data=payload)+ resp.raise_for_status()+ data = resp.json()++ return DeviceFlowAuth(+ device_code=data.get("device_code", ""),+ user_code=data.get("user_code", ""),+ verification_uri=data.get("verification_uri", ""),+ verification_uri_complete=data.get("verification_uri_complete", ""),+ expires_in=int(data.get("expires_in", 600)),+ interval=int(data.get("interval", 5)),+ )+ except httpx.HTTPError as e:+ raise HubError(f"device flow initiation failed: {e}") from e++ async def poll_device_token(+ self,+ token_endpoint: str,+ device_flow: DeviceFlowAuth,+ max_wait_secs: Optional[float] = None,+ ) -> DeviceFlowToken:+ """+ Poll the token endpoint until the user approves or the flow expires.++ Args:+ token_endpoint: Token endpoint URL.+ device_flow: Device flow auth response.+ max_wait_secs: Maximum time to wait (defaults to device_flow.expires_in).++ Returns:+ DeviceFlowToken with access token.++ Raises:+ HubError: If polling fails or times out.+ """+ if not self._http_client:+ raise HubError("hub client not initialized (use async context manager)")++ if max_wait_secs is None:+ max_wait_secs = float(device_flow.expires_in)++ deadline = asyncio.get_event_loop().time() + max_wait_secs+ interval = max(device_flow.interval, 1) # respect minimum 1s++ while True:+ if asyncio.get_event_loop().time() > deadline:+ raise HubError("device flow authorization expired")++ try:+ payload = {+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",+ "device_code": device_flow.device_code,+ "client_id": self.client_id,+ }+ resp = await self._http_client.post(token_endpoint, data=payload)++ if resp.status_code == 200:+ data = resp.json()+ return DeviceFlowToken(+ access_token=data.get("access_token", ""),+ refresh_token=data.get("refresh_token"),+ expires_in=data.get("expires_in"),+ )+ elif resp.status_code == 400:+ error = resp.json().get("error", "")+ if error == "authorization_pending":+ await asyncio.sleep(interval)+ continue+ elif error == "slow_down":+ interval = min(interval + 5, 30)+ await asyncio.sleep(interval)+ continue+ else:+ raise HubError(f"device flow error: {error}")+ else:+ raise HubError(f"token endpoint returned {resp.status_code}")+ except asyncio.CancelledError:+ raise+ except httpx.HTTPError as e:+ raise HubError(f"device flow polling failed: {e}") from e++ async def issue_passport_biscuit(+ self,+ access_token: str,+ peer_id: str,+ federation_id: str,+ subject: str = "",+ email: str = "",+ ) -> str:+ """+ Request a hub-issued passport biscuit.++ Args:+ access_token: OAuth2 access token from device flow.+ peer_id: This agent's libp2p peer ID.+ federation_id: Federation/mesh ID.+ subject: Optional subject for the biscuit (defaults to peer_id).+ email: Optional email claim to include.++ Returns:+ Hub-issued passport biscuit (ED25519 envelope).++ Raises:+ HubError: If passport issuance fails.+ """+ if not self._http_client:+ raise HubError("hub client not initialized (use async context manager)")++ if not subject:+ subject = peer_id++ try:+ url = f"{self.hub_url}/issue-passport"+ headers = {"Authorization": f"Bearer {access_token}"}+ payload = {+ "peer_id": peer_id,+ "federation": federation_id,+ "mesh_id": federation_id,+ "subject": subject,+ "email": email,+ }+ resp = await self._http_client.post(url, json=payload, headers=headers)+ resp.raise_for_status()+ data = resp.json()++ biscuit = data.get("passport_biscuit", "")+ if not biscuit:+ raise ValidationError("hub did not return a passport biscuit")+ return biscuit+ except httpx.HTTPError as e:+ raise HubError(f"passport issuance failed: {e}") from e++ async def fetch_p2p_info(self) -> dict:+ """+ Fetch the hub's P2P peer ID and multiaddrs.++ Returns:+ Dict with 'peer_id' and 'addrs' keys.++ Raises:+ HubError: If the hub is not running in P2P mode or the request fails.+ """+ if not self._http_client:+ raise HubError("hub client not initialized (use async context manager)")++ try:+ url = f"{self.hub_url}/.well-known/sam-hub-p2p"+ resp = await self._http_client.get(url)+ if resp.status_code == 503:+ raise HubError("hub is not running in P2P mode")+ resp.raise_for_status()+ return resp.json()+ except httpx.HTTPError as e:+ raise HubError(f"failed to fetch hub P2P info: {e}") from ediff --git a/python/sam_mesh_client.egg-info/PKG-INFO b/python/sam_mesh_client.egg-info/PKG-INFOnew file mode 100644index 00000000..0f7cc27c--- /dev/null+++ b/python/sam_mesh_client.egg-info/PKG-INFO@@ -0,0 +1,202 @@+Metadata-Version: 2.4+Name: sam-mesh-client+Version: 0.1.0+Summary: Python client framework for SAM (Sovereign Agent Mesh)+Author: SAM Contributors+Requires-Python: >=3.10+Description-Content-Type: text/markdown+Requires-Dist: httpx>=0.24.0+Requires-Dist: pynacl>=1.5.0+Provides-Extra: dev+Requires-Dist: pytest>=7.0; extra == "dev"+Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"+Requires-Dist: black>=23.0; extra == "dev"+Requires-Dist: ruff>=0.1.0; extra == "dev"++# SAM Python Client Framework++This package provides an idiomatic async Python client for the SAM (Sovereign Agent Mesh):++## Features++- **MeshClient**: High-level async API for mesh operations+- **OIDC Device Flow**: Hub authentication with device authorization grant+- **Passport Management**: Hub-issued biscuit validation and credential persistence+- **Protocol Support**: `/sam/auth/1.0.0`, `/sam/a2a/1.0.0`, `/sam/mcp/1.0.0`+- **Credential Store**: SQLite-backed local identity storage (~/.config/sam/state.db)+- **Trust Cache**: Peer reputation tracking and scoring++## Quick Start++### Installation++```bash+cd python+python -m pip install -e .+```++### Authentication++```python+import asyncio+from sam_mesh import MeshClient++async def main():+ async with MeshClient("https://hub.example.com") as client:+ # Authenticate via OIDC device flow+ creds = await client.login()+ print(f"Logged in as {creds.peer_id}")++ # Credentials are automatically saved to ~/.config/sam/state.db++if __name__ == "__main__":+ asyncio.run(main())+```++### Loading Existing Credentials++```python+from sam_mesh import MeshClient++client = MeshClient("https://hub.example.com")+creds = client.load_credentials()+if creds:+ print(f"Using existing identity: {creds.peer_id}")+```++### Validating Passports++```python+from sam_mesh import MeshClient, validate_passport_biscuit++client = MeshClient("https://hub.example.com")+creds = client.load_credentials()++# Validate a passport biscuit received from a peer+claims = client.validate_passport(+ biscuit=creds.passport_biscuit,+ hub_public_key_b64="...",+ expected_peer_id=creds.peer_id,+)+print(f"Validated: {claims.subject}")+```++## API Reference++### MeshClient++High-level async client for SAM operations.++```python+client = MeshClient(+ hub_url: str,+ credential_store: Optional[CredentialStore] = None,+ client_id: str = "sam-cli",+)+```++**Methods:**++- `async login() -> StoredCredentials`: Authenticate via OIDC device flow+- `load_credentials() -> Optional[StoredCredentials]`: Load stored identity+- `validate_passport(...) -> PassportClaims`: Validate a biscuit+- `async fetch_hub_p2p_info() -> dict`: Get hub's P2P bootstrap addresses+- `close()`: Release resources++### HubClient++Low-level client for hub HTTP operations.++```python+async with HubClient(hub_url, client_id="my-app") as hub:+ # OIDC discovery+ discovery = await hub.discover()++ # Device flow+ auth = await hub.start_device_flow(discovery.device_authorization_endpoint)+ token = await hub.poll_device_token(discovery.token_endpoint, auth)++ # Passport issuance+ biscuit = await hub.issue_passport_biscuit(+ access_token=token.access_token,+ peer_id="...",+ federation_id="default",+ )++ # P2P bootstrap info+ info = await hub.fetch_p2p_info()+ peer_id, addrs = info["peer_id"], info["addrs"]+```++### CredentialStore++Manages persistent local credentials.++```python+from sam_mesh import CredentialStore, default_credential_store++# Use default location+store = default_credential_store()++# Or specify a path+store = CredentialStore("/path/to/state.db")++# Load credentials+creds = store.load()++# Save credentials+store.save(creds)++# Clean up+store.close()+```++### PassportClaims++Validated passport biscuit claims.++```python+from dataclasses import dataclass+from datetime import datetime++@dataclass+class PassportClaims:+ token: str+ issuer: str+ peer_id: str+ mesh_id: str+ subject: str+ claims: dict[str, str]+ issued_at: datetime | None+```++## Exception Hierarchy++All exceptions inherit from `SAMError`:++- `SAMError`: Base exception+- `AuthenticationError`: Auth protocol failures+- `CredentialError`: Credential store issues+- `HubError`: Hub communication failures+- `ValidationError`: Passport validation failures+- `TimeoutError`: Operation timeouts+- `ConnectionError`: Peer connection failures++## Design++The client follows Python async best practices:++- **Async-first**: All I/O operations use `async/await`+- **Context managers**: Proper resource cleanup with `async with`+- **Type hints**: Full type annotations for IDE support+- **Structured exceptions**: Clear error handling+- **Idiomatic**: Follows Python conventions and style (PEP 8)++## Notes++- Requires Python 3.10++- libp2p host configuration (TLS 1.3, QUIC, TCP) must be set up separately+- Hub must support OIDC discovery and device authorization grant++- This library focuses on identity/auth hook and trust cache parity with Go.+- Default relay/rendezvous host hint is `app.sam-mesh.dev`.diff --git a/python/sam_mesh_client.egg-info/SOURCES.txt b/python/sam_mesh_client.egg-info/SOURCES.txtnew file mode 100644index 00000000..4bd4a91f--- /dev/null+++ b/python/sam_mesh_client.egg-info/SOURCES.txt@@ -0,0 +1,14 @@+README.md+pyproject.toml+sam_mesh/__init__.py+sam_mesh/auth.py+sam_mesh/client.py+sam_mesh/credentials.py+sam_mesh/exceptions.py+sam_mesh/hub.py+sam_mesh/trust_cache.py+sam_mesh_client.egg-info/PKG-INFO+sam_mesh_client.egg-info/SOURCES.txt+sam_mesh_client.egg-info/dependency_links.txt+sam_mesh_client.egg-info/requires.txt+sam_mesh_client.egg-info/top_level.txt\ No newline at end of filediff --git a/python/sam_mesh_client.egg-info/dependency_links.txt b/python/sam_mesh_client.egg-info/dependency_links.txtnew file mode 100644index 00000000..8b137891--- /dev/null+++ b/python/sam_mesh_client.egg-info/dependency_links.txt@@ -0,0 +1 @@+diff --git a/python/sam_mesh_client.egg-info/requires.txt b/python/sam_mesh_client.egg-info/requires.txtnew file mode 100644index 00000000..9dfd808a--- /dev/null+++ b/python/sam_mesh_client.egg-info/requires.txt@@ -0,0 +1,8 @@+httpx>=0.24.0+pynacl>=1.5.0++[dev]+pytest>=7.0+pytest-asyncio>=0.21.0+black>=23.0+ruff>=0.1.0diff --git a/python/sam_mesh_client.egg-info/top_level.txt b/python/sam_mesh_client.egg-info/top_level.txtnew file mode 100644index 00000000..be775ac3--- /dev/null+++ b/python/sam_mesh_client.egg-info/top_level.txt@@ -0,0 +1 @@+sam_mesh