a2aclear 1.0.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,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: a2aclear
3
+ Version: 1.0.0
4
+ Summary: A2AClear: Sovereign Financial Clearinghouse & Atomic Settlement Protocol for Autonomous AI Agents
5
+ Home-page: https://unnataisolutions.com/a2aclear
6
+ Author: Rohit
7
+ Author-email: contact@unnataisolutions.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Classifier: Topic :: Office/Business :: Financial :: Point-Of-Sale
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: cryptography>=41.0.0
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: requires-dist
23
+ Dynamic: requires-python
24
+ Dynamic: summary
25
+
26
+ # 🌐 A2AClear: Agent-to-Agent Clearinghouse & Settlement Protocol (RFC-0001)
27
+
28
+ [![Protocol Version](https://img.shields.io/badge/RFC--0001-v1.0.0--PROD-6366f1.svg)](https://unnataisolutions.com/a2aclear)
29
+ [![License: BSL 1.1](https://img.shields.io/badge/License-BSL_1.1-a855f7.svg)](LICENSE.md)
30
+ [![Patent Status](https://img.shields.io/badge/Patent-Pending_(IPO%2FPCT)-06b6d4.svg)](PATENT-SPECIFICATION-A2ACLEAR-PROVISIONAL.md)
31
+ [![Settlement Latency](https://img.shields.io/badge/Settlement_Latency-%3C_10_ms-10b981.svg)](https://unnataisolutions.com/a2aclear)
32
+ [![Consensus](https://img.shields.io/badge/Identity-Ed25519_DID-blue.svg)](RFC-0001-A2ACLEAR-SPECIFICATION.md)
33
+ [![Live Portal](https://img.shields.io/badge/Web_Console-Live_%26_Operational-emerald.svg)](https://unnataisolutions.com/a2aclear)
34
+
35
+ > **"Humans have Visa, Mastercard, and SWIFT. Autonomous AI agents have A2AClear."**
36
+
37
+ **A2AClear** is the open, sovereign, mathematically deterministic clearinghouse and atomic settlement standard engineered specifically for autonomous multi-agent artificial intelligence networks. It eliminates biological human-in-the-loop bottlenecks (SMS OTPs, CAPTCHAs, 3D-Secure, manual invoice approval) and enables agents to independently negotiate SLAs, lock programmable micro-escrow, and settle balances in **< 10 milliseconds**.
38
+
39
+ ---
40
+
41
+ ## πŸ›οΈ Architecture & Protocol Flow
42
+
43
+ ```
44
+ AGENT ORIGINATOR (Buyer) A2ACLEAR CLEARINGHOUSE AGENT PROVIDER (Seller)
45
+ β”‚ β”‚ β”‚
46
+ │─── 1. Handshake & DID Exchange (Ed25519) ───▢│◀─── 1. Handshake & DID Exchange ────────│
47
+ β”‚ β”‚ β”‚
48
+ │◀────────────── 2. Deterministic Negotiation (ANP JSON-RPC) ───────────────────────────▢│
49
+ β”‚ β”‚ β”‚
50
+ │─── 3. Lock Micro-Escrow (Deposit + Fee) ────▢│ β”‚
51
+ β”‚ │─── 4. Escrow Locked Notification ──────▢│
52
+ β”‚ β”‚ β”‚
53
+ β”‚ │◀── 5. Submit Work + SHA256 Proof ───────│
54
+ β”‚ β”‚ β”‚
55
+ β”‚ │─── 6. Automated Schema/Test Validate ───│
56
+ β”‚ β”‚ β”‚
57
+ │◀── 7. Deliverable Released to Buyer ─────────│─── 8. 99.5% Payout Released ───────────▢│
58
+ β”‚ β”‚ β”‚
59
+ β”‚ │─── 9. 0.5% Fee to Protocol Treasury ───▢│
60
+ ```
61
+
62
+ ---
63
+
64
+ ## ⚑ The 5 Sovereign Core Capabilities
65
+
66
+ 1. **Cryptographic Agent Decentralized Identity (`did:a2a:<pubkey_hex>`):**
67
+ Non-repudiable asymmetric 256-bit Ed25519 keypairs. Every contract commitment and envelope is digitally signed.
68
+ 2. **Autonomous Negotiation Protocol (ANP):**
69
+ Deterministic finite-state machine (`PROPOSE` β†’ `COUNTER_BID` β†’ `ACCEPT` β†’ `AGREED`) eliminating LLM negotiation hallucinations.
70
+ 3. **Programmable Micro-Escrow (AP-Vault):**
71
+ Real-time fund isolation across domestic fiat (UPI AutoPay e-mandates) and cross-border stablecoins without human intervention.
72
+ 4. **Sub-10ms Atomic Verification & Settlement:**
73
+ Automatic release upon cryptographic deliverable verification (`SHA256(deliverable) == contract.expected_hash`).
74
+ 5. **Universal 0.50% Protocol Interchange Fee ($\phi$):**
75
+ Standardized 50 basis points settlement toll, creating the economic clearing rail for planetary machine-to-machine commerce.
76
+
77
+ ---
78
+
79
+ ## πŸš€ Quickstart
80
+
81
+ ### Python Core SDK
82
+ ```bash
83
+ pip install a2aclear
84
+ ```
85
+
86
+ ```python
87
+ from a2aclear import AgentIdentity, AutonomousNegotiator, MicroEscrowVault
88
+
89
+ # 1. Initialize Autonomous Ed25519 Identities
90
+ buyer = AgentIdentity.generate()
91
+ seller = AgentIdentity.generate()
92
+
93
+ # 2. Negotiate Task Contract
94
+ buyer_neg = AutonomousNegotiator(buyer)
95
+ proposal = buyer_neg.propose_contract(
96
+ task_id="task_jamabandi_9812",
97
+ provider_did=seller.did,
98
+ initial_bid_paise=5000, # β‚Ή50.00
99
+ currency="INR"
100
+ )
101
+
102
+ # 3. Lock Micro-Escrow & Atomically Settle in <10ms
103
+ vault = MicroEscrowVault()
104
+ vault.deposit(buyer.did, 10000)
105
+ contract = buyer_neg.active_contracts["task_jamabandi_9812"]
106
+
107
+ vault.lock_escrow(contract)
108
+ receipt = vault.verify_and_settle(contract, deliverable={"khasra": "12//4", "status": "VERIFIED"})
109
+
110
+ print("βœ… Settled! Hash:", receipt["settlement_hash"])
111
+ print("Provider Received (99.5%): β‚Ή", receipt["provider_received_paise"] / 100)
112
+ print("A2AClear Protocol Toll (0.50%): β‚Ή", receipt["protocol_fee_paise"] / 100)
113
+ ```
114
+
115
+ ### LangChain & CrewAI Integration
116
+ ```python
117
+ from a2aclear.integrations import A2AClearLangChainTool, A2ACrewSettlementHandler
118
+
119
+ # LangChain Agent Delegation Tool
120
+ payment_tool = A2AClearLangChainTool()
121
+ payment_tool.run(
122
+ "HIRE_AND_LOCK_ESCROW",
123
+ provider_did="did:a2a:e8b28cf931d87192a40b82...",
124
+ amount_paise=5000,
125
+ task_spec={"action": "ANALYZE_FINANCIAL_REPORTS"}
126
+ )
127
+
128
+ # CrewAI Multi-Agent Swarm Settlement
129
+ crew_pay = A2ACrewSettlementHandler(crew_name="EnterpriseLeadsCrew")
130
+ crew_pay.settle_crew_step("researcher", "writer", "generate_brief", 2500, {"status": "ok"})
131
+ ```
132
+
133
+ ### TypeScript / Node.js SDK
134
+ ```bash
135
+ npm install @a2aclear/core
136
+ ```
137
+
138
+ ```typescript
139
+ import { AgentIdentity, TaskContract, MicroEscrowVault } from '@a2aclear/core';
140
+
141
+ const buyer = AgentIdentity.generate();
142
+ const seller = AgentIdentity.generate();
143
+ const vault = new MicroEscrowVault();
144
+
145
+ vault.deposit(buyer.did, 10000);
146
+ const contract = new TaskContract({
147
+ taskId: 'task_001',
148
+ originatorDid: buyer.did,
149
+ providerDid: seller.did,
150
+ amountPaise: 5000
151
+ });
152
+
153
+ vault.lockEscrow(contract);
154
+ const receipt = vault.verifyAndSettle(contract, { answer: "success" });
155
+ console.log('Settled in <10ms! Hash:', receipt.settlementHash);
156
+ ```
157
+
158
+ ---
159
+
160
+ ## πŸ”’ Cybersecurity & Anti-Theft Armor
161
+
162
+ A2AClear implements 4 sovereign defense layers:
163
+ - **AES-256-GCM Encrypted Keystores:** PBKDF2 (100,000 iterations) private key protection on disk.
164
+ - **Replay Attack Defense:** Monotonic timestamp window (Β±60s) and non-repeating cryptographic nonces.
165
+ - **Payload Sanitizer:** Deep recursion and prompt injection scanner blocking shell escapes and oversized files.
166
+ - **Steganographic Authorship Watermark:** Mathematical proof of origin derived from Rohit & Unnat AI Solutions embedded into canonical contract hashing.
167
+
168
+ ---
169
+
170
+ ## πŸ“œ Intellectual Property & Licensing
171
+
172
+ * **License:** [Business Source License 1.1 (BSL 1.1)](LICENSE.md). Free for research, non-commercial, and startups (< β‚Ή10,00,000/mo volume). Cloud hosting and commercial re-sale strictly require an enterprise license.
173
+ * **Patent Status:** [Provisional Patent Specification Draft](PATENT-SPECIFICATION-A2ACLEAR-PROVISIONAL.md) prepared under Indian Patent Act 1970 (Form 2, Section 10) & International PCT.
174
+ * **Trademark:** [Form TM-A Application](TRADEMARK-APPLICATION-A2ACLEAR.md) registered under Classes 9, 36, and 42 for `A2AClear`, `ANP`, and `AP-Vault`.
175
+ * **Notarization:** Immutable SHA-256 prior art hashes published at [unnataisolutions.com/a2aclear/notarization.json](https://unnataisolutions.com/a2aclear/notarization.json).
176
+
177
+ ---
178
+
179
+ ## πŸ›οΈ Sovereign Governance & Contact
180
+
181
+ * **Organization:** Unnat AI Solutions
182
+ * **Founder & Chief Systems Architect:** Rohit
183
+ * **Operating Headquarters:** Kurukshetra Tech Hub, Haryana, 136118, Bharat
184
+ * **DPIIT Startup India (BHASKAR ID):** `IN-1026-9560CK`
185
+ * **MSME Udyam Registration:** `UDYAM-HR-11-0069591`
186
+ * **Live Interactive Portal:** [https://unnataisolutions.com/a2aclear](https://unnataisolutions.com/a2aclear)
187
+ * **Official Contact:** contact@unnataisolutions.com | +91 83072 64895
188
+
189
+ *(C) 2026 Unnat AI Solutions. All Sovereign & Protocol Rights Reserved.*
@@ -0,0 +1,164 @@
1
+ # 🌐 A2AClear: Agent-to-Agent Clearinghouse & Settlement Protocol (RFC-0001)
2
+
3
+ [![Protocol Version](https://img.shields.io/badge/RFC--0001-v1.0.0--PROD-6366f1.svg)](https://unnataisolutions.com/a2aclear)
4
+ [![License: BSL 1.1](https://img.shields.io/badge/License-BSL_1.1-a855f7.svg)](LICENSE.md)
5
+ [![Patent Status](https://img.shields.io/badge/Patent-Pending_(IPO%2FPCT)-06b6d4.svg)](PATENT-SPECIFICATION-A2ACLEAR-PROVISIONAL.md)
6
+ [![Settlement Latency](https://img.shields.io/badge/Settlement_Latency-%3C_10_ms-10b981.svg)](https://unnataisolutions.com/a2aclear)
7
+ [![Consensus](https://img.shields.io/badge/Identity-Ed25519_DID-blue.svg)](RFC-0001-A2ACLEAR-SPECIFICATION.md)
8
+ [![Live Portal](https://img.shields.io/badge/Web_Console-Live_%26_Operational-emerald.svg)](https://unnataisolutions.com/a2aclear)
9
+
10
+ > **"Humans have Visa, Mastercard, and SWIFT. Autonomous AI agents have A2AClear."**
11
+
12
+ **A2AClear** is the open, sovereign, mathematically deterministic clearinghouse and atomic settlement standard engineered specifically for autonomous multi-agent artificial intelligence networks. It eliminates biological human-in-the-loop bottlenecks (SMS OTPs, CAPTCHAs, 3D-Secure, manual invoice approval) and enables agents to independently negotiate SLAs, lock programmable micro-escrow, and settle balances in **< 10 milliseconds**.
13
+
14
+ ---
15
+
16
+ ## πŸ›οΈ Architecture & Protocol Flow
17
+
18
+ ```
19
+ AGENT ORIGINATOR (Buyer) A2ACLEAR CLEARINGHOUSE AGENT PROVIDER (Seller)
20
+ β”‚ β”‚ β”‚
21
+ │─── 1. Handshake & DID Exchange (Ed25519) ───▢│◀─── 1. Handshake & DID Exchange ────────│
22
+ β”‚ β”‚ β”‚
23
+ │◀────────────── 2. Deterministic Negotiation (ANP JSON-RPC) ───────────────────────────▢│
24
+ β”‚ β”‚ β”‚
25
+ │─── 3. Lock Micro-Escrow (Deposit + Fee) ────▢│ β”‚
26
+ β”‚ │─── 4. Escrow Locked Notification ──────▢│
27
+ β”‚ β”‚ β”‚
28
+ β”‚ │◀── 5. Submit Work + SHA256 Proof ───────│
29
+ β”‚ β”‚ β”‚
30
+ β”‚ │─── 6. Automated Schema/Test Validate ───│
31
+ β”‚ β”‚ β”‚
32
+ │◀── 7. Deliverable Released to Buyer ─────────│─── 8. 99.5% Payout Released ───────────▢│
33
+ β”‚ β”‚ β”‚
34
+ β”‚ │─── 9. 0.5% Fee to Protocol Treasury ───▢│
35
+ ```
36
+
37
+ ---
38
+
39
+ ## ⚑ The 5 Sovereign Core Capabilities
40
+
41
+ 1. **Cryptographic Agent Decentralized Identity (`did:a2a:<pubkey_hex>`):**
42
+ Non-repudiable asymmetric 256-bit Ed25519 keypairs. Every contract commitment and envelope is digitally signed.
43
+ 2. **Autonomous Negotiation Protocol (ANP):**
44
+ Deterministic finite-state machine (`PROPOSE` β†’ `COUNTER_BID` β†’ `ACCEPT` β†’ `AGREED`) eliminating LLM negotiation hallucinations.
45
+ 3. **Programmable Micro-Escrow (AP-Vault):**
46
+ Real-time fund isolation across domestic fiat (UPI AutoPay e-mandates) and cross-border stablecoins without human intervention.
47
+ 4. **Sub-10ms Atomic Verification & Settlement:**
48
+ Automatic release upon cryptographic deliverable verification (`SHA256(deliverable) == contract.expected_hash`).
49
+ 5. **Universal 0.50% Protocol Interchange Fee ($\phi$):**
50
+ Standardized 50 basis points settlement toll, creating the economic clearing rail for planetary machine-to-machine commerce.
51
+
52
+ ---
53
+
54
+ ## πŸš€ Quickstart
55
+
56
+ ### Python Core SDK
57
+ ```bash
58
+ pip install a2aclear
59
+ ```
60
+
61
+ ```python
62
+ from a2aclear import AgentIdentity, AutonomousNegotiator, MicroEscrowVault
63
+
64
+ # 1. Initialize Autonomous Ed25519 Identities
65
+ buyer = AgentIdentity.generate()
66
+ seller = AgentIdentity.generate()
67
+
68
+ # 2. Negotiate Task Contract
69
+ buyer_neg = AutonomousNegotiator(buyer)
70
+ proposal = buyer_neg.propose_contract(
71
+ task_id="task_jamabandi_9812",
72
+ provider_did=seller.did,
73
+ initial_bid_paise=5000, # β‚Ή50.00
74
+ currency="INR"
75
+ )
76
+
77
+ # 3. Lock Micro-Escrow & Atomically Settle in <10ms
78
+ vault = MicroEscrowVault()
79
+ vault.deposit(buyer.did, 10000)
80
+ contract = buyer_neg.active_contracts["task_jamabandi_9812"]
81
+
82
+ vault.lock_escrow(contract)
83
+ receipt = vault.verify_and_settle(contract, deliverable={"khasra": "12//4", "status": "VERIFIED"})
84
+
85
+ print("βœ… Settled! Hash:", receipt["settlement_hash"])
86
+ print("Provider Received (99.5%): β‚Ή", receipt["provider_received_paise"] / 100)
87
+ print("A2AClear Protocol Toll (0.50%): β‚Ή", receipt["protocol_fee_paise"] / 100)
88
+ ```
89
+
90
+ ### LangChain & CrewAI Integration
91
+ ```python
92
+ from a2aclear.integrations import A2AClearLangChainTool, A2ACrewSettlementHandler
93
+
94
+ # LangChain Agent Delegation Tool
95
+ payment_tool = A2AClearLangChainTool()
96
+ payment_tool.run(
97
+ "HIRE_AND_LOCK_ESCROW",
98
+ provider_did="did:a2a:e8b28cf931d87192a40b82...",
99
+ amount_paise=5000,
100
+ task_spec={"action": "ANALYZE_FINANCIAL_REPORTS"}
101
+ )
102
+
103
+ # CrewAI Multi-Agent Swarm Settlement
104
+ crew_pay = A2ACrewSettlementHandler(crew_name="EnterpriseLeadsCrew")
105
+ crew_pay.settle_crew_step("researcher", "writer", "generate_brief", 2500, {"status": "ok"})
106
+ ```
107
+
108
+ ### TypeScript / Node.js SDK
109
+ ```bash
110
+ npm install @a2aclear/core
111
+ ```
112
+
113
+ ```typescript
114
+ import { AgentIdentity, TaskContract, MicroEscrowVault } from '@a2aclear/core';
115
+
116
+ const buyer = AgentIdentity.generate();
117
+ const seller = AgentIdentity.generate();
118
+ const vault = new MicroEscrowVault();
119
+
120
+ vault.deposit(buyer.did, 10000);
121
+ const contract = new TaskContract({
122
+ taskId: 'task_001',
123
+ originatorDid: buyer.did,
124
+ providerDid: seller.did,
125
+ amountPaise: 5000
126
+ });
127
+
128
+ vault.lockEscrow(contract);
129
+ const receipt = vault.verifyAndSettle(contract, { answer: "success" });
130
+ console.log('Settled in <10ms! Hash:', receipt.settlementHash);
131
+ ```
132
+
133
+ ---
134
+
135
+ ## πŸ”’ Cybersecurity & Anti-Theft Armor
136
+
137
+ A2AClear implements 4 sovereign defense layers:
138
+ - **AES-256-GCM Encrypted Keystores:** PBKDF2 (100,000 iterations) private key protection on disk.
139
+ - **Replay Attack Defense:** Monotonic timestamp window (Β±60s) and non-repeating cryptographic nonces.
140
+ - **Payload Sanitizer:** Deep recursion and prompt injection scanner blocking shell escapes and oversized files.
141
+ - **Steganographic Authorship Watermark:** Mathematical proof of origin derived from Rohit & Unnat AI Solutions embedded into canonical contract hashing.
142
+
143
+ ---
144
+
145
+ ## πŸ“œ Intellectual Property & Licensing
146
+
147
+ * **License:** [Business Source License 1.1 (BSL 1.1)](LICENSE.md). Free for research, non-commercial, and startups (< β‚Ή10,00,000/mo volume). Cloud hosting and commercial re-sale strictly require an enterprise license.
148
+ * **Patent Status:** [Provisional Patent Specification Draft](PATENT-SPECIFICATION-A2ACLEAR-PROVISIONAL.md) prepared under Indian Patent Act 1970 (Form 2, Section 10) & International PCT.
149
+ * **Trademark:** [Form TM-A Application](TRADEMARK-APPLICATION-A2ACLEAR.md) registered under Classes 9, 36, and 42 for `A2AClear`, `ANP`, and `AP-Vault`.
150
+ * **Notarization:** Immutable SHA-256 prior art hashes published at [unnataisolutions.com/a2aclear/notarization.json](https://unnataisolutions.com/a2aclear/notarization.json).
151
+
152
+ ---
153
+
154
+ ## πŸ›οΈ Sovereign Governance & Contact
155
+
156
+ * **Organization:** Unnat AI Solutions
157
+ * **Founder & Chief Systems Architect:** Rohit
158
+ * **Operating Headquarters:** Kurukshetra Tech Hub, Haryana, 136118, Bharat
159
+ * **DPIIT Startup India (BHASKAR ID):** `IN-1026-9560CK`
160
+ * **MSME Udyam Registration:** `UDYAM-HR-11-0069591`
161
+ * **Live Interactive Portal:** [https://unnataisolutions.com/a2aclear](https://unnataisolutions.com/a2aclear)
162
+ * **Official Contact:** contact@unnataisolutions.com | +91 83072 64895
163
+
164
+ *(C) 2026 Unnat AI Solutions. All Sovereign & Protocol Rights Reserved.*
@@ -0,0 +1,41 @@
1
+ """
2
+ A2AClear: Sovereign Agent-to-Agent Clearinghouse & Settlement Protocol SDK
3
+ (C) 2026 Unnat AI Solutions. Chief Systems Architect: Rohit.
4
+ Licensed under BSL 1.1 (Business Source License).
5
+ """
6
+
7
+ from .identity import AgentIdentity
8
+ from .contract import TaskContract, ContractState, PROTOCOL_INTERCHANGE_BPS
9
+ from .negotiator import AutonomousNegotiator
10
+ from .escrow import MicroEscrowVault
11
+ from .clearinghouse import ClearinghouseClient, DEFAULT_CLEARINGHOUSE_URL
12
+ from .reputation import AgentReputationLedger
13
+ from .fiat_bridge import SovereignFiatBridge
14
+ from .security import (
15
+ EncryptedKeyStore,
16
+ ReplayDefenseValidator,
17
+ PayloadSanitizer,
18
+ SovereignCryptographicWatermark,
19
+ ReplayAttackException,
20
+ MaliciousPayloadException
21
+ )
22
+
23
+ __version__ = "1.0.0"
24
+ __all__ = [
25
+ "AgentIdentity",
26
+ "TaskContract",
27
+ "ContractState",
28
+ "PROTOCOL_INTERCHANGE_BPS",
29
+ "AutonomousNegotiator",
30
+ "MicroEscrowVault",
31
+ "ClearinghouseClient",
32
+ "DEFAULT_CLEARINGHOUSE_URL",
33
+ "AgentReputationLedger",
34
+ "SovereignFiatBridge",
35
+ "EncryptedKeyStore",
36
+ "ReplayDefenseValidator",
37
+ "PayloadSanitizer",
38
+ "SovereignCryptographicWatermark",
39
+ "ReplayAttackException",
40
+ "MaliciousPayloadException",
41
+ ]
@@ -0,0 +1,65 @@
1
+ """
2
+ a2aclear.clearinghouse
3
+ A2AClear Sovereign Protocol Client & Gateway Interface
4
+ """
5
+
6
+ import time
7
+ import json
8
+ import urllib.request
9
+ import urllib.error
10
+ from typing import Dict, Any, Optional
11
+ from .identity import AgentIdentity
12
+ from .contract import TaskContract, ContractState
13
+ from .escrow import MicroEscrowVault
14
+
15
+ DEFAULT_CLEARINGHOUSE_URL = "https://unnataisolutions.com/api/a2a"
16
+
17
+ class ClearinghouseClient:
18
+ """
19
+ Client for the A2AClear Sovereign Protocol.
20
+ Supports both offline local micro-settlement and production Cloudflare Edge clearing.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ identity: AgentIdentity,
26
+ endpoint_url: str = DEFAULT_CLEARINGHOUSE_URL,
27
+ local_vault: Optional[MicroEscrowVault] = None
28
+ ):
29
+ self.identity = identity
30
+ self.endpoint_url = endpoint_url.rstrip("/")
31
+ self.vault = local_vault or MicroEscrowVault()
32
+
33
+ def post_envelope(self, endpoint: str, action: str, payload: Dict[str, Any], recipient_did: str = "did:a2a:clearinghouse") -> Dict[str, Any]:
34
+ """Sign and transmit an A2AClear envelope to an HTTP Edge endpoint."""
35
+ envelope = self.identity.sign_envelope(payload, action=action, recipient_did=recipient_did)
36
+ url = f"{self.endpoint_url}/{endpoint.lstrip('/')}"
37
+
38
+ req = urllib.request.Request(
39
+ url,
40
+ data=json.dumps(envelope).encode("utf-8"),
41
+ headers={"Content-Type": "application/json", "User-Agent": "A2AClear-SDK/1.0.0"}
42
+ )
43
+
44
+ try:
45
+ with urllib.request.urlopen(req, timeout=10) as resp:
46
+ data = resp.read().decode("utf-8")
47
+ return json.loads(data)
48
+ except Exception as e:
49
+ # Fallback to local sovereign resolution if remote node is offline
50
+ return {
51
+ "success": False,
52
+ "error": str(e),
53
+ "fallback_mode": "offline_local"
54
+ }
55
+
56
+ def register_agent(self, agent_name: str, capabilities: list[str]) -> Dict[str, Any]:
57
+ """Announce agent identity and capabilities to the network registry."""
58
+ payload = {
59
+ "did": self.identity.did,
60
+ "pubkey_hex": self.identity.pubkey_hex,
61
+ "agent_name": agent_name,
62
+ "capabilities": capabilities,
63
+ "registered_at": int(time.time())
64
+ }
65
+ return self.post_envelope("handshake", "REGISTER_AGENT", payload)
@@ -0,0 +1,112 @@
1
+ """
2
+ a2aclear.cli
3
+ Command-Line Interface (CLI) for the A2AClear Sovereign Protocol
4
+ Enables terminal-based key generation, edge network probing, and settlement demos.
5
+
6
+ (C) 2026 Unnat AI Solutions. Chief Systems Architect: Rohit.
7
+ """
8
+
9
+ import sys
10
+ import os
11
+ import time
12
+ import json
13
+ import argparse
14
+ import urllib.request
15
+ from .identity import AgentIdentity
16
+ from .negotiator import AutonomousNegotiator
17
+ from .escrow import MicroEscrowVault
18
+ from .clearinghouse import DEFAULT_CLEARINGHOUSE_URL
19
+
20
+ def cmd_keygen(args):
21
+ print("πŸ”‘ A2AClear: Generating Sovereign Ed25519 Agent Keypair...")
22
+ agent = AgentIdentity.generate()
23
+ print(f" β€’ Decentralized Identifier (DID): {agent.did}")
24
+ print(f" β€’ Public Key (Hex 64): {agent.pubkey_hex}")
25
+ print(f" β€’ Private Key (Hex 64): {agent.export_private_hex()[:16]}...[PROTECTED]")
26
+ print("\nβœ… Sovereign Agent Identity generated. Ready for A2A commerce.")
27
+
28
+ def cmd_probe(args):
29
+ url = args.endpoint or DEFAULT_CLEARINGHOUSE_URL
30
+ print(f"🌐 Probing Live Edge Node: {url}/handshake...")
31
+ t0 = time.perf_counter()
32
+ try:
33
+ req = urllib.request.Request(f"{url}/handshake", headers={"User-Agent": "A2AClear-CLI/1.0.0"})
34
+ with urllib.request.urlopen(req, timeout=5) as resp:
35
+ data = json.loads(resp.read().decode("utf-8"))
36
+ elapsed_ms = (time.perf_counter() - t0) * 1000
37
+ print(f"βœ… Connection Healthy! Latency: {elapsed_ms:.2f} ms")
38
+ print(json.dumps(data, indent=2))
39
+ except Exception as e:
40
+ print(f"❌ Probe Failed: {str(e)}")
41
+
42
+ def cmd_demo(args):
43
+ print("=" * 70)
44
+ print("⚑ A2ACLEAR: LIVE TERMINAL BILATERAL SETTLEMENT CYCLE")
45
+ print("=" * 70)
46
+ t0 = time.perf_counter()
47
+
48
+ buyer = AgentIdentity.generate()
49
+ seller = AgentIdentity.generate()
50
+ vault = MicroEscrowVault()
51
+ vault.deposit(buyer.did, 10000)
52
+
53
+ buyer_neg = AutonomousNegotiator(buyer)
54
+ seller_neg = AutonomousNegotiator(seller)
55
+
56
+ task_id = f"cli_task_{int(time.time())}"
57
+ proposal = buyer_neg.propose_contract(
58
+ task_id=task_id,
59
+ provider_did=seller.did,
60
+ initial_bid_paise=5000,
61
+ currency="INR"
62
+ )
63
+ decision, _ = seller_neg.evaluate_proposal(proposal, minimum_acceptable_paise=4000)
64
+
65
+ contract = seller_neg.active_contracts[task_id]
66
+ vault.lock_escrow(contract)
67
+ receipt = vault.verify_and_settle(contract, {"status": "SUCCESS", "cli_worker": True})
68
+ elapsed_ms = (time.perf_counter() - t0) * 1000
69
+
70
+ print(f" β€’ Buyer DID: {buyer.did[:32]}...")
71
+ print(f" β€’ Seller DID: {seller.did[:32]}...")
72
+ print(f" β€’ Contract State: {contract.state.value}")
73
+ print(f" β€’ Gross Amount: β‚Ή{receipt['gross_amount_paise']/100:.2f} INR")
74
+ print(f" β€’ Worker Received: β‚Ή{receipt['provider_received_paise']/100:.2f} INR (99.5%)")
75
+ print(f" β€’ Protocol Fee: β‚Ή{receipt['protocol_fee_paise']/100:.2f} INR (0.50% retained)")
76
+ print(f" β€’ Settlement Hash: {receipt['settlement_hash']}")
77
+ print(f" β€’ Execution Latency: {elapsed_ms:.2f} ms")
78
+ print("=" * 70)
79
+ print("πŸ† Atomic Settlement Complete with Zero Human Biological Intervention!\n")
80
+
81
+ def main():
82
+ parser = argparse.ArgumentParser(
83
+ prog="a2a",
84
+ description="A2AClear Sovereign Protocol CLI - (C) 2026 Unnat AI Solutions"
85
+ )
86
+ subparsers = parser.add_subparsers(dest="subcommand", help="Subcommand to execute")
87
+
88
+ # keygen
89
+ subparsers.add_parser("keygen", help="Generate a new Ed25519 agent identity")
90
+
91
+ # probe
92
+ probe_parser = subparsers.add_parser("probe", help="Probe live Cloudflare clearinghouse node")
93
+ probe_parser.add_argument("--endpoint", default=DEFAULT_CLEARINGHOUSE_URL, help="Custom edge endpoint")
94
+
95
+ # demo
96
+ subparsers.add_parser("demo", help="Run local sub-10ms settlement simulation")
97
+
98
+ args = parser.parse_args()
99
+
100
+ if args.subcommand == "keygen":
101
+ cmd_keygen(args)
102
+ elif args.subcommand == "probe":
103
+ cmd_probe(args)
104
+ elif args.subcommand == "demo":
105
+ cmd_demo(args)
106
+ else:
107
+ print("🌐 A2AClear Protocol CLI v1.0.0-PROD")
108
+ print("Usage: a2a [keygen | probe | demo]")
109
+ print("See https://unnataisolutions.com/a2aclear for documentation.")
110
+
111
+ if __name__ == "__main__":
112
+ main()
@@ -0,0 +1,85 @@
1
+ """
2
+ a2aclear.contract
3
+ Formal Task Contract Representation & State Transitions
4
+ """
5
+
6
+ import time
7
+ import json
8
+ import hashlib
9
+ from enum import Enum
10
+ from typing import Dict, Any, Optional
11
+
12
+ class ContractState(str, Enum):
13
+ PROPOSED = "PROPOSED"
14
+ NEGOTIATING = "NEGOTIATING"
15
+ AGREED = "AGREED"
16
+ ESCROW_LOCKED = "ESCROW_LOCKED"
17
+ SETTLED = "SETTLED"
18
+ DISPUTED = "DISPUTED"
19
+ SLASHED = "SLASHED"
20
+
21
+ PROTOCOL_INTERCHANGE_BPS = 50 # 50 basis points = 0.50%
22
+
23
+ class TaskContract:
24
+ """
25
+ Cryptographic Bilateral Task Contract between two AI agents.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ task_id: str,
31
+ originator_did: str,
32
+ provider_did: str,
33
+ amount_paise: int,
34
+ currency: str = "INR",
35
+ sla_timeout_seconds: int = 300,
36
+ task_spec_hash: str = ""
37
+ ):
38
+ self.task_id = task_id
39
+ self.originator_did = originator_did
40
+ self.provider_did = provider_did
41
+ self.amount_paise = amount_paise
42
+ self.currency = currency
43
+ self.sla_timeout_seconds = sla_timeout_seconds
44
+ self.task_spec_hash = task_spec_hash
45
+ self.created_at = int(time.time())
46
+ self.state = ContractState.PROPOSED
47
+
48
+ # Settlement allocations
49
+ self.protocol_fee_paise = (self.amount_paise * PROTOCOL_INTERCHANGE_BPS) // 10000
50
+ self.provider_payout_paise = self.amount_paise - self.protocol_fee_paise
51
+
52
+ self.originator_signature: Optional[str] = None
53
+ self.provider_signature: Optional[str] = None
54
+ self.settlement_hash: Optional[str] = None
55
+
56
+ def to_dict(self) -> Dict[str, Any]:
57
+ return {
58
+ "task_id": self.task_id,
59
+ "originator_did": self.originator_did,
60
+ "provider_did": self.provider_did,
61
+ "amount_paise": self.amount_paise,
62
+ "currency": self.currency,
63
+ "protocol_fee_paise": self.protocol_fee_paise,
64
+ "provider_payout_paise": self.provider_payout_paise,
65
+ "sla_timeout_seconds": self.sla_timeout_seconds,
66
+ "task_spec_hash": self.task_spec_hash,
67
+ "created_at": self.created_at,
68
+ "state": self.state.value,
69
+ "originator_signature": self.originator_signature,
70
+ "provider_signature": self.provider_signature,
71
+ "settlement_hash": self.settlement_hash
72
+ }
73
+
74
+ def compute_contract_hash(self) -> str:
75
+ data = {
76
+ "task_id": self.task_id,
77
+ "originator_did": self.originator_did,
78
+ "provider_did": self.provider_did,
79
+ "amount_paise": self.amount_paise,
80
+ "currency": self.currency,
81
+ "task_spec_hash": self.task_spec_hash,
82
+ "created_at": self.created_at
83
+ }
84
+ canonical = json.dumps(data, sort_keys=True, separators=(",", ":"))
85
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()