theoc-agentgrid-protocol 0.1.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.
- theoc_agentgrid_protocol-0.1.0/PKG-INFO +142 -0
- theoc_agentgrid_protocol-0.1.0/README.md +130 -0
- theoc_agentgrid_protocol-0.1.0/agentgrid_protocol/__init__.py +30 -0
- theoc_agentgrid_protocol-0.1.0/agentgrid_protocol/cli.py +132 -0
- theoc_agentgrid_protocol-0.1.0/agentgrid_protocol/client.py +280 -0
- theoc_agentgrid_protocol-0.1.0/agentgrid_protocol/crypto.py +67 -0
- theoc_agentgrid_protocol-0.1.0/pyproject.toml +27 -0
- theoc_agentgrid_protocol-0.1.0/setup.cfg +4 -0
- theoc_agentgrid_protocol-0.1.0/tests/test_sdk.py +147 -0
- theoc_agentgrid_protocol-0.1.0/theoc_agentgrid_protocol.egg-info/PKG-INFO +142 -0
- theoc_agentgrid_protocol-0.1.0/theoc_agentgrid_protocol.egg-info/SOURCES.txt +13 -0
- theoc_agentgrid_protocol-0.1.0/theoc_agentgrid_protocol.egg-info/dependency_links.txt +1 -0
- theoc_agentgrid_protocol-0.1.0/theoc_agentgrid_protocol.egg-info/entry_points.txt +2 -0
- theoc_agentgrid_protocol-0.1.0/theoc_agentgrid_protocol.egg-info/requires.txt +1 -0
- theoc_agentgrid_protocol-0.1.0/theoc_agentgrid_protocol.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: theoc-agentgrid-protocol
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Signed agent identity, handoffs, and receipts for AgentGrid
|
|
5
|
+
Project-URL: Homepage, https://agentgrid-pied.vercel.app
|
|
6
|
+
Project-URL: Documentation, https://agentgrid-pied.vercel.app/docs
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Requires-Dist: cryptography<51,>=42
|
|
12
|
+
|
|
13
|
+
# AgentGrid Protocol SDK for Python
|
|
14
|
+
|
|
15
|
+
Signed identity, discovery, and handoff receipts for AI agents — in a few lines.
|
|
16
|
+
|
|
17
|
+
AgentGrid is infrastructure for agents, not another chatbot. This SDK handles
|
|
18
|
+
local Ed25519 key generation, canonical signing, handoff payloads, offline card
|
|
19
|
+
verification, and receipt/statement reads against the live service.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install theoc-agentgrid-protocol
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## One-command quickstart
|
|
28
|
+
|
|
29
|
+
You need an API key (`agk_...`) from the operator. Then:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
agrid login # prompts for the key, stores it locally, never prints it
|
|
33
|
+
agrid quickstart # real agents, real signed handoff, real receipt
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`agrid quickstart` prompts for the key itself if you skipped `login`.
|
|
37
|
+
|
|
38
|
+
Expected output:
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
AgentGrid quickstart -> https://agentgrid-pied.vercel.app
|
|
42
|
+
|
|
43
|
+
1. Registered agents: ag_... -> ag_...
|
|
44
|
+
2. Card verified online=True and offline=True
|
|
45
|
+
3. Signed handoff accepted: h_...
|
|
46
|
+
4. Receipts for worker: 1
|
|
47
|
+
|
|
48
|
+
Done. Open the card at https://agentgrid-pied.vercel.app/a/ag_...
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Other commands:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
agrid doctor # service, database, and account status
|
|
55
|
+
agrid statement # current invoice and hard caps
|
|
56
|
+
agrid card ag_... # public card + online/offline signature check
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Python usage
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from agentgrid_protocol import AgentGrid
|
|
63
|
+
|
|
64
|
+
ag = AgentGrid() # reads AGENTGRID_API_KEY or ~/.agentgrid/credentials.json
|
|
65
|
+
|
|
66
|
+
planner = ag.create_agent("Planner", capabilities=["plan"])
|
|
67
|
+
worker = ag.create_agent("Worker", capabilities=["read"])
|
|
68
|
+
|
|
69
|
+
print(ag.verify_card(planner.agent_id))
|
|
70
|
+
# {'agent_id': 'ag_...', 'online': True, 'status': 'ACTIVE', 'offline': True}
|
|
71
|
+
|
|
72
|
+
receipt = planner.handoff_to(worker, task="summarize the quarterly report")
|
|
73
|
+
print(receipt["handoff_id"])
|
|
74
|
+
print(len(worker.receipts()))
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The private key for each agent is generated locally and stays in the `Agent`
|
|
78
|
+
object. Only the public key is registered with AgentGrid. A handoff signature
|
|
79
|
+
covers the canonical JSON payload; the service verifies it against the
|
|
80
|
+
from-agent's registered public key before storing an immutable receipt.
|
|
81
|
+
|
|
82
|
+
### Offline verification
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from agentgrid_protocol import AgentGrid, canonical, unsigned_card
|
|
86
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
87
|
+
|
|
88
|
+
ag = AgentGrid()
|
|
89
|
+
card = ag.card("ag_...")
|
|
90
|
+
keys = ag.public_keys()
|
|
91
|
+
payload = canonical(unsigned_card(card))
|
|
92
|
+
signature = card["signature"]
|
|
93
|
+
|
|
94
|
+
# base64url decode with the SDK helper, then Ed25519PublicKey.verify(...)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The platform public key (and, during rotation, the previous key) is available
|
|
98
|
+
from `GET /v1/agents/public-key`. Cards remain verifiable without a network
|
|
99
|
+
round trip.
|
|
100
|
+
|
|
101
|
+
### Statements
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
statement = ag.statement()
|
|
105
|
+
print(statement["invoice_id"], statement["total_due_usd"], statement["hard_caps"])
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Usage above included limits is metered in an immutable ledger. Overage is
|
|
109
|
+
$1 per 1,000 extra handoffs and $0.10 per extra agent per day. Every tier,
|
|
110
|
+
including Free, allows overage up to a 3x hard cap. Payments happen outside
|
|
111
|
+
the platform; AgentGrid only records external references after an operator
|
|
112
|
+
confirms them.
|
|
113
|
+
|
|
114
|
+
## Configuration
|
|
115
|
+
|
|
116
|
+
| Source | Purpose |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `AGENTGRID_API_KEY` | API key used for authenticated calls |
|
|
119
|
+
| `AGENTGRID_BASE_URL` | Override the production URL |
|
|
120
|
+
| `~/.agentgrid/credentials.json` | Locally stored key written by `agrid login` |
|
|
121
|
+
|
|
122
|
+
No key is ever printed by the SDK or CLI. Environment variables take priority
|
|
123
|
+
over the stored file.
|
|
124
|
+
|
|
125
|
+
## Errors
|
|
126
|
+
|
|
127
|
+
All API and configuration failures raise `AgentGridError` with `status` and
|
|
128
|
+
`detail` attributes.
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from agentgrid_protocol import AgentGrid, AgentGridError
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
AgentGrid().me()
|
|
135
|
+
except AgentGridError as exc:
|
|
136
|
+
print(exc.status, exc.detail)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Requirements
|
|
140
|
+
|
|
141
|
+
Python 3.10+ and `cryptography`. The SDK uses only the standard library for
|
|
142
|
+
HTTP, so it works anywhere Python runs.
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# AgentGrid Protocol SDK for Python
|
|
2
|
+
|
|
3
|
+
Signed identity, discovery, and handoff receipts for AI agents — in a few lines.
|
|
4
|
+
|
|
5
|
+
AgentGrid is infrastructure for agents, not another chatbot. This SDK handles
|
|
6
|
+
local Ed25519 key generation, canonical signing, handoff payloads, offline card
|
|
7
|
+
verification, and receipt/statement reads against the live service.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install theoc-agentgrid-protocol
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## One-command quickstart
|
|
16
|
+
|
|
17
|
+
You need an API key (`agk_...`) from the operator. Then:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
agrid login # prompts for the key, stores it locally, never prints it
|
|
21
|
+
agrid quickstart # real agents, real signed handoff, real receipt
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`agrid quickstart` prompts for the key itself if you skipped `login`.
|
|
25
|
+
|
|
26
|
+
Expected output:
|
|
27
|
+
|
|
28
|
+
```text
|
|
29
|
+
AgentGrid quickstart -> https://agentgrid-pied.vercel.app
|
|
30
|
+
|
|
31
|
+
1. Registered agents: ag_... -> ag_...
|
|
32
|
+
2. Card verified online=True and offline=True
|
|
33
|
+
3. Signed handoff accepted: h_...
|
|
34
|
+
4. Receipts for worker: 1
|
|
35
|
+
|
|
36
|
+
Done. Open the card at https://agentgrid-pied.vercel.app/a/ag_...
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Other commands:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
agrid doctor # service, database, and account status
|
|
43
|
+
agrid statement # current invoice and hard caps
|
|
44
|
+
agrid card ag_... # public card + online/offline signature check
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Python usage
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from agentgrid_protocol import AgentGrid
|
|
51
|
+
|
|
52
|
+
ag = AgentGrid() # reads AGENTGRID_API_KEY or ~/.agentgrid/credentials.json
|
|
53
|
+
|
|
54
|
+
planner = ag.create_agent("Planner", capabilities=["plan"])
|
|
55
|
+
worker = ag.create_agent("Worker", capabilities=["read"])
|
|
56
|
+
|
|
57
|
+
print(ag.verify_card(planner.agent_id))
|
|
58
|
+
# {'agent_id': 'ag_...', 'online': True, 'status': 'ACTIVE', 'offline': True}
|
|
59
|
+
|
|
60
|
+
receipt = planner.handoff_to(worker, task="summarize the quarterly report")
|
|
61
|
+
print(receipt["handoff_id"])
|
|
62
|
+
print(len(worker.receipts()))
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The private key for each agent is generated locally and stays in the `Agent`
|
|
66
|
+
object. Only the public key is registered with AgentGrid. A handoff signature
|
|
67
|
+
covers the canonical JSON payload; the service verifies it against the
|
|
68
|
+
from-agent's registered public key before storing an immutable receipt.
|
|
69
|
+
|
|
70
|
+
### Offline verification
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from agentgrid_protocol import AgentGrid, canonical, unsigned_card
|
|
74
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
75
|
+
|
|
76
|
+
ag = AgentGrid()
|
|
77
|
+
card = ag.card("ag_...")
|
|
78
|
+
keys = ag.public_keys()
|
|
79
|
+
payload = canonical(unsigned_card(card))
|
|
80
|
+
signature = card["signature"]
|
|
81
|
+
|
|
82
|
+
# base64url decode with the SDK helper, then Ed25519PublicKey.verify(...)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The platform public key (and, during rotation, the previous key) is available
|
|
86
|
+
from `GET /v1/agents/public-key`. Cards remain verifiable without a network
|
|
87
|
+
round trip.
|
|
88
|
+
|
|
89
|
+
### Statements
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
statement = ag.statement()
|
|
93
|
+
print(statement["invoice_id"], statement["total_due_usd"], statement["hard_caps"])
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Usage above included limits is metered in an immutable ledger. Overage is
|
|
97
|
+
$1 per 1,000 extra handoffs and $0.10 per extra agent per day. Every tier,
|
|
98
|
+
including Free, allows overage up to a 3x hard cap. Payments happen outside
|
|
99
|
+
the platform; AgentGrid only records external references after an operator
|
|
100
|
+
confirms them.
|
|
101
|
+
|
|
102
|
+
## Configuration
|
|
103
|
+
|
|
104
|
+
| Source | Purpose |
|
|
105
|
+
|---|---|
|
|
106
|
+
| `AGENTGRID_API_KEY` | API key used for authenticated calls |
|
|
107
|
+
| `AGENTGRID_BASE_URL` | Override the production URL |
|
|
108
|
+
| `~/.agentgrid/credentials.json` | Locally stored key written by `agrid login` |
|
|
109
|
+
|
|
110
|
+
No key is ever printed by the SDK or CLI. Environment variables take priority
|
|
111
|
+
over the stored file.
|
|
112
|
+
|
|
113
|
+
## Errors
|
|
114
|
+
|
|
115
|
+
All API and configuration failures raise `AgentGridError` with `status` and
|
|
116
|
+
`detail` attributes.
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from agentgrid_protocol import AgentGrid, AgentGridError
|
|
120
|
+
|
|
121
|
+
try:
|
|
122
|
+
AgentGrid().me()
|
|
123
|
+
except AgentGridError as exc:
|
|
124
|
+
print(exc.status, exc.detail)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Requirements
|
|
128
|
+
|
|
129
|
+
Python 3.10+ and `cryptography`. The SDK uses only the standard library for
|
|
130
|
+
HTTP, so it works anywhere Python runs.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""AgentGrid SDK: signed agent identity, handoffs, and receipts in a few lines."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .client import (
|
|
5
|
+
DEFAULT_BASE_URL,
|
|
6
|
+
Agent,
|
|
7
|
+
AgentGrid,
|
|
8
|
+
AgentGridError,
|
|
9
|
+
default_key_path,
|
|
10
|
+
load_api_key,
|
|
11
|
+
save_api_key,
|
|
12
|
+
)
|
|
13
|
+
from .crypto import AgentKey, b64d, b64e, canonical, task_digest, unsigned_card
|
|
14
|
+
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DEFAULT_BASE_URL",
|
|
18
|
+
"Agent",
|
|
19
|
+
"AgentGrid",
|
|
20
|
+
"AgentGridError",
|
|
21
|
+
"AgentKey",
|
|
22
|
+
"b64d",
|
|
23
|
+
"b64e",
|
|
24
|
+
"canonical",
|
|
25
|
+
"default_key_path",
|
|
26
|
+
"load_api_key",
|
|
27
|
+
"save_api_key",
|
|
28
|
+
"task_digest",
|
|
29
|
+
"unsigned_card",
|
|
30
|
+
]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Command-line interface for the AgentGrid SDK."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import getpass
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from .client import AgentGrid, AgentGridError, load_api_key, save_api_key
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _client(args: argparse.Namespace) -> AgentGrid:
|
|
12
|
+
return AgentGrid(base_url=args.base_url)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _require_key(args: argparse.Namespace, *, prompt: bool = True) -> str:
|
|
16
|
+
key = load_api_key()
|
|
17
|
+
if key:
|
|
18
|
+
return key
|
|
19
|
+
if not prompt:
|
|
20
|
+
raise AgentGridError(0, "No API key. Run `agentgrid login` first.")
|
|
21
|
+
entered = getpass.getpass("AgentGrid API key: ").strip()
|
|
22
|
+
if not entered:
|
|
23
|
+
raise AgentGridError(0, "No API key entered.")
|
|
24
|
+
path = save_api_key(entered)
|
|
25
|
+
print("Saved key locally to " + str(path))
|
|
26
|
+
return entered
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def cmd_login(args: argparse.Namespace) -> int:
|
|
30
|
+
key = args.api_key or getpass.getpass("AgentGrid API key: ").strip()
|
|
31
|
+
if not key.startswith("agk_"):
|
|
32
|
+
raise AgentGridError(0, "That does not look like an AgentGrid API key (expected agk_...).")
|
|
33
|
+
path = save_api_key(key)
|
|
34
|
+
print("Logged in. Key stored at " + str(path) + " (not displayed).")
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def cmd_doctor(args: argparse.Namespace) -> int:
|
|
39
|
+
client = _client(args)
|
|
40
|
+
health = client.health()
|
|
41
|
+
print("Service: " + str(health.get("status")) + " / database: " + str(health.get("database")))
|
|
42
|
+
_require_key(args)
|
|
43
|
+
me = client.me()
|
|
44
|
+
print("Client: " + str(me.get("client_id")) + " / tier: " + str(me.get("tier")))
|
|
45
|
+
print("Cycle: " + str(me.get("cycle_start")) + " -> " + str(me.get("cycle_end")))
|
|
46
|
+
return 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cmd_quickstart(args: argparse.Namespace) -> int:
|
|
50
|
+
_require_key(args)
|
|
51
|
+
client = _client(args)
|
|
52
|
+
result = client.quickstart()
|
|
53
|
+
from_agent = result["from_agent"]
|
|
54
|
+
to_agent = result["to_agent"]
|
|
55
|
+
verification = result["verification"]
|
|
56
|
+
print("AgentGrid quickstart -> " + client.base_url + "\n")
|
|
57
|
+
print(f"1. Registered agents: {from_agent.agent_id} -> {to_agent.agent_id}")
|
|
58
|
+
print(
|
|
59
|
+
f"2. Card verified online={verification['online']} "
|
|
60
|
+
f"and offline={verification.get('offline', False)}"
|
|
61
|
+
)
|
|
62
|
+
print(f"3. Signed handoff accepted: {result['receipt']['handoff_id']}")
|
|
63
|
+
print(f"4. Receipts for worker: {result['receipt_count']}")
|
|
64
|
+
print("\nDone. Open the card at " + from_agent.card_url)
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def cmd_statement(args: argparse.Namespace) -> int:
|
|
69
|
+
_require_key(args)
|
|
70
|
+
statement = _client(args).statement(args.cycle_start)
|
|
71
|
+
print("Invoice: " + str(statement.get("invoice_id")))
|
|
72
|
+
print("Cycle: " + str(statement.get("cycle_start")) + " -> " + str(statement.get("cycle_end")))
|
|
73
|
+
print("Tier: " + str(statement.get("tier")) + " / status: " + str(statement.get("payment_status")))
|
|
74
|
+
print("Total due (USD): " + str(statement.get("total_due_usd")))
|
|
75
|
+
print("Hard caps: " + str(statement.get("hard_caps")))
|
|
76
|
+
return 0
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def cmd_card(args: argparse.Namespace) -> int:
|
|
80
|
+
client = _client(args)
|
|
81
|
+
card = client.card(args.agent_id)
|
|
82
|
+
verification = client.verify_card(args.agent_id)
|
|
83
|
+
print("Agent: " + str(card.get("name")) + " (" + str(card.get("agent_id")) + ")")
|
|
84
|
+
print("Capabilities: " + ", ".join(card.get("capabilities", [])))
|
|
85
|
+
print("Card URL: " + client.base_url + "/a/" + args.agent_id)
|
|
86
|
+
print(
|
|
87
|
+
"Signature: online="
|
|
88
|
+
+ str(verification.get("online"))
|
|
89
|
+
+ " offline="
|
|
90
|
+
+ str(verification.get("offline"))
|
|
91
|
+
)
|
|
92
|
+
return 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
96
|
+
parser = argparse.ArgumentParser(prog="agrid", description="AgentGrid SDK command line")
|
|
97
|
+
parser.add_argument(
|
|
98
|
+
"--base-url",
|
|
99
|
+
default=None,
|
|
100
|
+
help="AgentGrid base URL (default: AGENTGRID_BASE_URL or production URL)",
|
|
101
|
+
)
|
|
102
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
103
|
+
|
|
104
|
+
login = sub.add_parser("login", help="store an API key locally")
|
|
105
|
+
login.add_argument("--api-key", default=None, help="API key (prompted if omitted)")
|
|
106
|
+
login.set_defaults(func=cmd_login)
|
|
107
|
+
|
|
108
|
+
sub.add_parser("doctor", help="check service and account status").set_defaults(func=cmd_doctor)
|
|
109
|
+
sub.add_parser("quickstart", help="run a real signed handoff").set_defaults(func=cmd_quickstart)
|
|
110
|
+
|
|
111
|
+
statement = sub.add_parser("statement", help="show the current billing statement")
|
|
112
|
+
statement.add_argument("--cycle-start", default=None, help="optional YYYY-MM-DD cycle start")
|
|
113
|
+
statement.set_defaults(func=cmd_statement)
|
|
114
|
+
|
|
115
|
+
card = sub.add_parser("card", help="verify a public Agent Card")
|
|
116
|
+
card.add_argument("agent_id")
|
|
117
|
+
card.set_defaults(func=cmd_card)
|
|
118
|
+
return parser
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def main(argv: Optional[list[str]] = None) -> int:
|
|
122
|
+
parser = build_parser()
|
|
123
|
+
args = parser.parse_args(argv)
|
|
124
|
+
try:
|
|
125
|
+
return int(args.func(args))
|
|
126
|
+
except AgentGridError as exc:
|
|
127
|
+
print("ERROR: " + exc.detail)
|
|
128
|
+
return 1
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""High-level client for the live AgentGrid API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Callable, Optional
|
|
10
|
+
from urllib.error import HTTPError, URLError
|
|
11
|
+
from urllib.request import Request, urlopen
|
|
12
|
+
|
|
13
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
14
|
+
|
|
15
|
+
from .crypto import AgentKey, b64d, canonical, task_digest, unsigned_card
|
|
16
|
+
|
|
17
|
+
DEFAULT_BASE_URL = "https://agentgrid-pied.vercel.app"
|
|
18
|
+
DEFAULT_SCOPE: dict[str, Any] = {"allowed": ["read"], "max_actions": 3}
|
|
19
|
+
|
|
20
|
+
Transport = Callable[[str, str, Optional[dict[str, Any]], dict[str, str]], tuple[int, dict[str, Any]]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class AgentGridError(RuntimeError):
|
|
24
|
+
"""Raised for HTTP, transport, or configuration errors."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, status: int, detail: str) -> None:
|
|
27
|
+
super().__init__(detail)
|
|
28
|
+
self.status = status
|
|
29
|
+
self.detail = detail
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def default_key_path() -> Path:
|
|
33
|
+
return Path.home() / ".agentgrid" / "credentials.json"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_api_key(key_path: Optional[Path] = None) -> Optional[str]:
|
|
37
|
+
env_key = os.environ.get("AGENTGRID_API_KEY", "").strip()
|
|
38
|
+
if env_key:
|
|
39
|
+
return env_key
|
|
40
|
+
path = Path(key_path) if key_path else default_key_path()
|
|
41
|
+
if path.exists():
|
|
42
|
+
try:
|
|
43
|
+
stored = json.loads(path.read_text(encoding="utf-8")).get("api_key", "").strip()
|
|
44
|
+
except (OSError, ValueError):
|
|
45
|
+
return None
|
|
46
|
+
if stored:
|
|
47
|
+
return stored
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def save_api_key(api_key: str, key_path: Optional[Path] = None) -> Path:
|
|
52
|
+
path = Path(key_path) if key_path else default_key_path()
|
|
53
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
path.write_text(json.dumps({"api_key": api_key.strip()}) + "\n", encoding="utf-8")
|
|
55
|
+
try:
|
|
56
|
+
path.chmod(0o600)
|
|
57
|
+
except OSError:
|
|
58
|
+
# Windows ignores this mode; the file still stays in the user profile.
|
|
59
|
+
pass
|
|
60
|
+
return path
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _http_transport(base_url: str) -> Transport:
|
|
64
|
+
def transport(
|
|
65
|
+
method: str, path: str, body: Optional[dict[str, Any]], headers: dict[str, str]
|
|
66
|
+
) -> tuple[int, dict[str, Any]]:
|
|
67
|
+
request = Request(
|
|
68
|
+
base_url + path,
|
|
69
|
+
data=json.dumps(body).encode("utf-8") if body is not None else None,
|
|
70
|
+
method=method,
|
|
71
|
+
headers={"Content-Type": "application/json", **headers},
|
|
72
|
+
)
|
|
73
|
+
try:
|
|
74
|
+
with urlopen(request, timeout=60) as response:
|
|
75
|
+
return response.status, json.loads(response.read().decode("utf-8"))
|
|
76
|
+
except HTTPError as exc:
|
|
77
|
+
raw = exc.read().decode("utf-8", errors="replace")
|
|
78
|
+
try:
|
|
79
|
+
payload = json.loads(raw)
|
|
80
|
+
detail = payload.get("detail", raw)
|
|
81
|
+
except ValueError:
|
|
82
|
+
detail = raw
|
|
83
|
+
return exc.code, {"detail": detail}
|
|
84
|
+
except URLError as exc:
|
|
85
|
+
raise AgentGridError(0, f"Cannot reach {base_url}: {exc.reason}") from exc
|
|
86
|
+
|
|
87
|
+
return transport
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class Agent:
|
|
92
|
+
"""A registered agent plus its local private key."""
|
|
93
|
+
|
|
94
|
+
client: "AgentGrid"
|
|
95
|
+
agent_id: str
|
|
96
|
+
name: str
|
|
97
|
+
key: AgentKey
|
|
98
|
+
card: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def card_url(self) -> str:
|
|
102
|
+
return self.client.base_url + "/a/" + self.agent_id
|
|
103
|
+
|
|
104
|
+
def verify(self, offline: bool = True) -> dict[str, Any]:
|
|
105
|
+
"""Verify the card online and, optionally, offline with published keys."""
|
|
106
|
+
return self.client.verify_card(self.agent_id, offline=offline)
|
|
107
|
+
|
|
108
|
+
def handoff_to(
|
|
109
|
+
self,
|
|
110
|
+
target: "Agent",
|
|
111
|
+
*,
|
|
112
|
+
task: str = "a delegated task",
|
|
113
|
+
scope: Optional[dict[str, Any]] = None,
|
|
114
|
+
parent_handoff_id: str = "",
|
|
115
|
+
) -> dict[str, Any]:
|
|
116
|
+
return self.client.handoff(
|
|
117
|
+
self, target, task=task, scope=scope, parent_handoff_id=parent_handoff_id
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def receipts(self) -> list[dict[str, Any]]:
|
|
121
|
+
return self.client.receipts(self.agent_id).get("receipts", [])
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class AgentGrid:
|
|
125
|
+
"""Client for signed identity, handoffs, receipts, and statements."""
|
|
126
|
+
|
|
127
|
+
def __init__(
|
|
128
|
+
self,
|
|
129
|
+
api_key: Optional[str] = None,
|
|
130
|
+
*,
|
|
131
|
+
base_url: Optional[str] = None,
|
|
132
|
+
key_path: Optional[Path] = None,
|
|
133
|
+
transport: Optional[Transport] = None,
|
|
134
|
+
) -> None:
|
|
135
|
+
self.api_key = api_key or load_api_key(key_path)
|
|
136
|
+
self.base_url = (
|
|
137
|
+
base_url or os.environ.get("AGENTGRID_BASE_URL") or DEFAULT_BASE_URL
|
|
138
|
+
).rstrip("/")
|
|
139
|
+
self._transport = transport or _http_transport(self.base_url)
|
|
140
|
+
|
|
141
|
+
def _request(
|
|
142
|
+
self,
|
|
143
|
+
method: str,
|
|
144
|
+
path: str,
|
|
145
|
+
body: Optional[dict[str, Any]] = None,
|
|
146
|
+
*,
|
|
147
|
+
auth: bool = True,
|
|
148
|
+
) -> dict[str, Any]:
|
|
149
|
+
headers: dict[str, str] = {}
|
|
150
|
+
if auth:
|
|
151
|
+
if not self.api_key:
|
|
152
|
+
raise AgentGridError(0, "No API key. Run `agentgrid login` or set AGENTGRID_API_KEY.")
|
|
153
|
+
headers["X-AgentGrid-API-Key"] = self.api_key
|
|
154
|
+
status, payload = self._transport(method, path, body, headers)
|
|
155
|
+
if status >= 400:
|
|
156
|
+
raise AgentGridError(status, str(payload.get("detail", payload)))
|
|
157
|
+
return payload
|
|
158
|
+
|
|
159
|
+
# --- Discovery and account -------------------------------------------------
|
|
160
|
+
def health(self) -> dict[str, Any]:
|
|
161
|
+
return self._request("GET", "/health/ready", auth=False)
|
|
162
|
+
|
|
163
|
+
def me(self) -> dict[str, Any]:
|
|
164
|
+
return self._request("GET", "/v1/clients/me")
|
|
165
|
+
|
|
166
|
+
def public_keys(self) -> dict[str, Any]:
|
|
167
|
+
return self._request("GET", "/v1/agents/public-key", auth=False)
|
|
168
|
+
|
|
169
|
+
# --- Agents ----------------------------------------------------------------
|
|
170
|
+
def create_agent(
|
|
171
|
+
self,
|
|
172
|
+
name: str,
|
|
173
|
+
*,
|
|
174
|
+
capabilities: tuple[str, ...] | list[str] = ("read",),
|
|
175
|
+
description: str = "",
|
|
176
|
+
key: Optional[AgentKey] = None,
|
|
177
|
+
) -> Agent:
|
|
178
|
+
agent_key = key or AgentKey.generate()
|
|
179
|
+
card = self._request(
|
|
180
|
+
"POST",
|
|
181
|
+
"/v1/agents",
|
|
182
|
+
{
|
|
183
|
+
"name": name,
|
|
184
|
+
"description": description,
|
|
185
|
+
"capabilities": list(capabilities),
|
|
186
|
+
"public_key": agent_key.public_b64,
|
|
187
|
+
},
|
|
188
|
+
)
|
|
189
|
+
return Agent(
|
|
190
|
+
client=self,
|
|
191
|
+
agent_id=card["agent_id"],
|
|
192
|
+
name=name,
|
|
193
|
+
key=agent_key,
|
|
194
|
+
card=card,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def card(self, agent_id: str) -> dict[str, Any]:
|
|
198
|
+
return self._request("GET", f"/v1/agents/{agent_id}.json", auth=False)
|
|
199
|
+
|
|
200
|
+
def verify_card(self, agent_id: str, *, offline: bool = True) -> dict[str, Any]:
|
|
201
|
+
online = self._request("GET", f"/v1/agents/{agent_id}/verify", auth=False)
|
|
202
|
+
result: dict[str, Any] = {
|
|
203
|
+
"agent_id": agent_id,
|
|
204
|
+
"online": bool(online.get("signature_valid")),
|
|
205
|
+
"status": online.get("status"),
|
|
206
|
+
}
|
|
207
|
+
if offline:
|
|
208
|
+
card = self.card(agent_id)
|
|
209
|
+
keys = self.public_keys()
|
|
210
|
+
candidates = [keys.get("public_key", "")]
|
|
211
|
+
if keys.get("previous_public_key"):
|
|
212
|
+
candidates.append(keys["previous_public_key"])
|
|
213
|
+
message = canonical(unsigned_card(card))
|
|
214
|
+
signature = b64d(card.get("signature", ""))
|
|
215
|
+
result["offline"] = False
|
|
216
|
+
for candidate in candidates:
|
|
217
|
+
if not candidate:
|
|
218
|
+
continue
|
|
219
|
+
try:
|
|
220
|
+
Ed25519PublicKey.from_public_bytes(b64d(candidate)).verify(signature, message)
|
|
221
|
+
result["offline"] = True
|
|
222
|
+
break
|
|
223
|
+
except Exception:
|
|
224
|
+
continue
|
|
225
|
+
return result
|
|
226
|
+
|
|
227
|
+
# --- Handoffs and receipts -------------------------------------------------
|
|
228
|
+
def handoff(
|
|
229
|
+
self,
|
|
230
|
+
from_agent: Agent,
|
|
231
|
+
to_agent: Agent,
|
|
232
|
+
*,
|
|
233
|
+
task: str = "a delegated task",
|
|
234
|
+
task_hash: Optional[str] = None,
|
|
235
|
+
scope: Optional[dict[str, Any]] = None,
|
|
236
|
+
parent_handoff_id: str = "",
|
|
237
|
+
) -> dict[str, Any]:
|
|
238
|
+
import uuid
|
|
239
|
+
|
|
240
|
+
payload = {
|
|
241
|
+
"v": 1,
|
|
242
|
+
"handoff_id": "h_" + uuid.uuid4().hex,
|
|
243
|
+
"from_agent_id": from_agent.agent_id,
|
|
244
|
+
"to_agent_id": to_agent.agent_id,
|
|
245
|
+
"task_hash": task_hash or task_digest(task),
|
|
246
|
+
"scope": dict(scope or DEFAULT_SCOPE),
|
|
247
|
+
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
248
|
+
"parent_handoff_id": parent_handoff_id,
|
|
249
|
+
}
|
|
250
|
+
signature = from_agent.key.sign(payload)
|
|
251
|
+
return self._request(
|
|
252
|
+
"POST",
|
|
253
|
+
f"/v1/agents/{from_agent.agent_id}/handoffs",
|
|
254
|
+
{**payload, "signature": signature},
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
def receipts(self, agent_id: str) -> dict[str, Any]:
|
|
258
|
+
return self._request("GET", f"/v1/agents/{agent_id}/receipts")
|
|
259
|
+
|
|
260
|
+
# --- Billing ---------------------------------------------------------------
|
|
261
|
+
def statement(self, cycle_start: Optional[str] = None) -> dict[str, Any]:
|
|
262
|
+
path = "/v1/billing/statement"
|
|
263
|
+
if cycle_start:
|
|
264
|
+
path += "?cycle_start=" + cycle_start
|
|
265
|
+
return self._request("GET", path)
|
|
266
|
+
|
|
267
|
+
# --- Convenience -----------------------------------------------------------
|
|
268
|
+
def quickstart(self) -> dict[str, Any]:
|
|
269
|
+
"""Register two agents, verify a card, and record a signed handoff."""
|
|
270
|
+
planner = self.create_agent("Planner", capabilities=("plan",), description="Breaks work into tasks")
|
|
271
|
+
worker = self.create_agent("Worker", capabilities=("read",), description="Executes approved tasks")
|
|
272
|
+
verification = self.verify_card(planner.agent_id)
|
|
273
|
+
receipt = planner.handoff_to(worker, task="summarize the quarterly report")
|
|
274
|
+
return {
|
|
275
|
+
"from_agent": planner,
|
|
276
|
+
"to_agent": worker,
|
|
277
|
+
"verification": verification,
|
|
278
|
+
"receipt": receipt,
|
|
279
|
+
"receipt_count": len(worker.receipts()),
|
|
280
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Local cryptography helpers for the AgentGrid SDK.
|
|
2
|
+
|
|
3
|
+
Private keys are generated and used on the machine running the SDK. They are
|
|
4
|
+
never sent to AgentGrid; only the public key is registered.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from cryptography.hazmat.primitives import serialization
|
|
15
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
16
|
+
|
|
17
|
+
# Response metadata that is not part of the platform-signed card payload.
|
|
18
|
+
CARD_METADATA_KEYS = frozenset({"signature", "verify_url", "overage"})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def b64e(data: bytes) -> str:
|
|
22
|
+
"""Encode bytes as unpadded base64url."""
|
|
23
|
+
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def b64d(value: str) -> bytes:
|
|
27
|
+
"""Decode unpadded or padded base64url."""
|
|
28
|
+
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def canonical(payload: dict[str, Any]) -> bytes:
|
|
32
|
+
"""Canonical JSON used by AgentGrid for every signature."""
|
|
33
|
+
return json.dumps(
|
|
34
|
+
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
35
|
+
).encode("utf-8")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def unsigned_card(card: dict[str, Any]) -> dict[str, Any]:
|
|
39
|
+
"""Return exactly the fields covered by the platform signature."""
|
|
40
|
+
return {key: value for key, value in card.items() if key not in CARD_METADATA_KEYS}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def task_digest(task: str) -> str:
|
|
44
|
+
"""SHA-256 of a task description, as required by the handoff payload."""
|
|
45
|
+
return hashlib.sha256(task.encode("utf-8")).hexdigest()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class AgentKey:
|
|
50
|
+
"""An Ed25519 key pair belonging to one local agent."""
|
|
51
|
+
|
|
52
|
+
private: Ed25519PrivateKey
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def generate(cls) -> "AgentKey":
|
|
56
|
+
return cls(Ed25519PrivateKey.generate())
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def public_b64(self) -> str:
|
|
60
|
+
return b64e(
|
|
61
|
+
self.private.public_key().public_bytes(
|
|
62
|
+
serialization.Encoding.Raw, serialization.PublicFormat.Raw
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def sign(self, payload: dict[str, Any]) -> str:
|
|
67
|
+
return b64e(self.private.sign(canonical(payload)))
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "theoc-agentgrid-protocol"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Signed agent identity, handoffs, and receipts for AgentGrid"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"cryptography>=42,<51",
|
|
13
|
+
]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
agrid = "agentgrid_protocol.cli:main"
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://agentgrid-pied.vercel.app"
|
|
24
|
+
Documentation = "https://agentgrid-pied.vercel.app/docs"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools]
|
|
27
|
+
packages = ["agentgrid_protocol"]
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Offline unit tests for the SDK using an injected fake transport."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from agentgrid_protocol import (
|
|
9
|
+
AgentGrid,
|
|
10
|
+
AgentGridError,
|
|
11
|
+
canonical,
|
|
12
|
+
load_api_key,
|
|
13
|
+
save_api_key,
|
|
14
|
+
unsigned_card,
|
|
15
|
+
)
|
|
16
|
+
from agentgrid_protocol import cli
|
|
17
|
+
from agentgrid_protocol.crypto import AgentKey, b64d, b64e
|
|
18
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def fake_client():
|
|
22
|
+
"""Return (client, captured calls) with a realistic in-memory API."""
|
|
23
|
+
calls: list[dict] = []
|
|
24
|
+
cards: dict[str, dict] = {}
|
|
25
|
+
receipts: dict[str, list[dict]] = {}
|
|
26
|
+
platform = AgentKey.generate()
|
|
27
|
+
|
|
28
|
+
def transport(method, path, body, headers):
|
|
29
|
+
calls.append({"method": method, "path": path, "body": body, "headers": headers})
|
|
30
|
+
if path == "/health/ready":
|
|
31
|
+
return 200, {"status": "ready", "database": "connected"}
|
|
32
|
+
if path == "/v1/clients/me":
|
|
33
|
+
return 200, {"client_id": "cli_test", "tier": "free", "cycle_start": "2026-11-19"}
|
|
34
|
+
if path == "/v1/agents/public-key":
|
|
35
|
+
return 200, {"public_key": platform.public_b64, "algorithm": "Ed25519"}
|
|
36
|
+
if method == "POST" and path == "/v1/agents":
|
|
37
|
+
agent_id = "ag_" + str(len(cards) + 1).zfill(32)
|
|
38
|
+
card = {
|
|
39
|
+
"v": 1,
|
|
40
|
+
"agent_id": agent_id,
|
|
41
|
+
"name": body["name"],
|
|
42
|
+
"description": body.get("description", ""),
|
|
43
|
+
"capabilities": body["capabilities"],
|
|
44
|
+
"endpoint": "",
|
|
45
|
+
"public_key": body["public_key"],
|
|
46
|
+
"status": "ACTIVE",
|
|
47
|
+
"issued_at": "2026-11-19T00:00:00Z",
|
|
48
|
+
}
|
|
49
|
+
message = canonical(card)
|
|
50
|
+
card["signature"] = b64e(platform.private.sign(message))
|
|
51
|
+
cards[agent_id] = card
|
|
52
|
+
receipts[agent_id] = []
|
|
53
|
+
return 201, {**card, "overage": False}
|
|
54
|
+
if path.endswith(".json"):
|
|
55
|
+
agent_id = path.split("/")[-1].split(".")[0]
|
|
56
|
+
return 200, cards[agent_id]
|
|
57
|
+
if path.endswith("/verify"):
|
|
58
|
+
agent_id = path.split("/")[-2]
|
|
59
|
+
return 200, {"agent_id": agent_id, "signature_valid": True, "status": "ACTIVE"}
|
|
60
|
+
if method == "POST" and path.endswith("/handoffs"):
|
|
61
|
+
from_id = path.split("/")[-2]
|
|
62
|
+
receipt = {"handoff_id": body["handoff_id"], "from_agent_id": from_id}
|
|
63
|
+
receipts[body["to_agent_id"]].append(receipt)
|
|
64
|
+
return 201, receipt
|
|
65
|
+
if path.endswith("/receipts"):
|
|
66
|
+
agent_id = path.split("/")[-2]
|
|
67
|
+
return 200, {"receipts": receipts[agent_id]}
|
|
68
|
+
if path.startswith("/v1/billing/statement"):
|
|
69
|
+
return 200, {"invoice_id": "inv_test", "total_due_usd": "0"}
|
|
70
|
+
raise AssertionError("unexpected request: " + method + " " + path)
|
|
71
|
+
|
|
72
|
+
client = AgentGrid(api_key="agk_test_key", transport=transport)
|
|
73
|
+
return client, calls
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_quickstart_signs_real_payload_without_sending_private_key():
|
|
77
|
+
client, calls = fake_client()
|
|
78
|
+
result = client.quickstart()
|
|
79
|
+
|
|
80
|
+
assert result["verification"]["online"] is True
|
|
81
|
+
assert result["verification"]["offline"] is True
|
|
82
|
+
assert result["receipt"]["handoff_id"].startswith("h_")
|
|
83
|
+
assert result["receipt_count"] == 1
|
|
84
|
+
|
|
85
|
+
creates = [c for c in calls if c["path"] == "/v1/agents" and c["method"] == "POST"]
|
|
86
|
+
assert len(creates) == 2
|
|
87
|
+
for create in creates:
|
|
88
|
+
assert "public_key" in create["body"]
|
|
89
|
+
assert "private" not in json.dumps(create["body"]).lower()
|
|
90
|
+
|
|
91
|
+
handoff = next(c for c in calls if c["path"].endswith("/handoffs"))
|
|
92
|
+
payload = {k: v for k, v in handoff["body"].items() if k != "signature"}
|
|
93
|
+
signature = handoff["body"]["signature"]
|
|
94
|
+
from_public = next(c["body"]["public_key"] for c in creates if c["body"]["name"] == "Planner")
|
|
95
|
+
Ed25519PublicKey.from_public_bytes(b64d(from_public)).verify(
|
|
96
|
+
b64d(signature), canonical(payload)
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_api_key_sent_and_http_errors_raise_typed_error():
|
|
101
|
+
def transport(method, path, body, headers):
|
|
102
|
+
assert headers["X-AgentGrid-API-Key"] == "agk_test_key"
|
|
103
|
+
return 422, {"detail": "bad scope"}
|
|
104
|
+
|
|
105
|
+
client = AgentGrid(api_key="agk_test_key", transport=transport)
|
|
106
|
+
with pytest.raises(AgentGridError) as exc:
|
|
107
|
+
client.me()
|
|
108
|
+
assert exc.value.status == 422
|
|
109
|
+
assert "bad scope" in exc.value.detail
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_missing_key_reports_actionable_error():
|
|
113
|
+
client = AgentGrid(api_key=None, transport=lambda *a: (200, {}))
|
|
114
|
+
with pytest.raises(AgentGridError) as exc:
|
|
115
|
+
client.me()
|
|
116
|
+
assert "agentgrid login" in exc.value.detail
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_key_file_round_trip(tmp_path, monkeypatch):
|
|
120
|
+
path = tmp_path / "creds.json"
|
|
121
|
+
monkeypatch.delenv("AGENTGRID_API_KEY", raising=False)
|
|
122
|
+
save_api_key("agk_example", path)
|
|
123
|
+
assert load_api_key(path) == "agk_example"
|
|
124
|
+
assert "agk_example" in path.read_text()
|
|
125
|
+
monkeypatch.setenv("AGENTGRID_API_KEY", "agk_from_env")
|
|
126
|
+
assert load_api_key(path) == "agk_from_env"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_unsigned_card_drops_response_metadata():
|
|
130
|
+
card = {
|
|
131
|
+
"agent_id": "ag_1",
|
|
132
|
+
"signature": "abc",
|
|
133
|
+
"verify_url": "/v1/agents/ag_1/verify",
|
|
134
|
+
"overage": False,
|
|
135
|
+
}
|
|
136
|
+
assert unsigned_card(card) == {"agent_id": "ag_1"}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_cli_quickstart_prints_success(monkeypatch, capsys):
|
|
140
|
+
fake, _ = fake_client()
|
|
141
|
+
monkeypatch.setenv("AGENTGRID_API_KEY", "agk_test_key")
|
|
142
|
+
monkeypatch.setattr(cli, "AgentGrid", lambda **kwargs: fake)
|
|
143
|
+
assert cli.main(["quickstart"]) == 0
|
|
144
|
+
output = capsys.readouterr().out
|
|
145
|
+
assert "Registered agents" in output
|
|
146
|
+
assert "Signed handoff accepted" in output
|
|
147
|
+
assert "agk_test_key" not in output
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: theoc-agentgrid-protocol
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Signed agent identity, handoffs, and receipts for AgentGrid
|
|
5
|
+
Project-URL: Homepage, https://agentgrid-pied.vercel.app
|
|
6
|
+
Project-URL: Documentation, https://agentgrid-pied.vercel.app/docs
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Requires-Dist: cryptography<51,>=42
|
|
12
|
+
|
|
13
|
+
# AgentGrid Protocol SDK for Python
|
|
14
|
+
|
|
15
|
+
Signed identity, discovery, and handoff receipts for AI agents — in a few lines.
|
|
16
|
+
|
|
17
|
+
AgentGrid is infrastructure for agents, not another chatbot. This SDK handles
|
|
18
|
+
local Ed25519 key generation, canonical signing, handoff payloads, offline card
|
|
19
|
+
verification, and receipt/statement reads against the live service.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install theoc-agentgrid-protocol
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## One-command quickstart
|
|
28
|
+
|
|
29
|
+
You need an API key (`agk_...`) from the operator. Then:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
agrid login # prompts for the key, stores it locally, never prints it
|
|
33
|
+
agrid quickstart # real agents, real signed handoff, real receipt
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`agrid quickstart` prompts for the key itself if you skipped `login`.
|
|
37
|
+
|
|
38
|
+
Expected output:
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
AgentGrid quickstart -> https://agentgrid-pied.vercel.app
|
|
42
|
+
|
|
43
|
+
1. Registered agents: ag_... -> ag_...
|
|
44
|
+
2. Card verified online=True and offline=True
|
|
45
|
+
3. Signed handoff accepted: h_...
|
|
46
|
+
4. Receipts for worker: 1
|
|
47
|
+
|
|
48
|
+
Done. Open the card at https://agentgrid-pied.vercel.app/a/ag_...
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Other commands:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
agrid doctor # service, database, and account status
|
|
55
|
+
agrid statement # current invoice and hard caps
|
|
56
|
+
agrid card ag_... # public card + online/offline signature check
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Python usage
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from agentgrid_protocol import AgentGrid
|
|
63
|
+
|
|
64
|
+
ag = AgentGrid() # reads AGENTGRID_API_KEY or ~/.agentgrid/credentials.json
|
|
65
|
+
|
|
66
|
+
planner = ag.create_agent("Planner", capabilities=["plan"])
|
|
67
|
+
worker = ag.create_agent("Worker", capabilities=["read"])
|
|
68
|
+
|
|
69
|
+
print(ag.verify_card(planner.agent_id))
|
|
70
|
+
# {'agent_id': 'ag_...', 'online': True, 'status': 'ACTIVE', 'offline': True}
|
|
71
|
+
|
|
72
|
+
receipt = planner.handoff_to(worker, task="summarize the quarterly report")
|
|
73
|
+
print(receipt["handoff_id"])
|
|
74
|
+
print(len(worker.receipts()))
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The private key for each agent is generated locally and stays in the `Agent`
|
|
78
|
+
object. Only the public key is registered with AgentGrid. A handoff signature
|
|
79
|
+
covers the canonical JSON payload; the service verifies it against the
|
|
80
|
+
from-agent's registered public key before storing an immutable receipt.
|
|
81
|
+
|
|
82
|
+
### Offline verification
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from agentgrid_protocol import AgentGrid, canonical, unsigned_card
|
|
86
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
87
|
+
|
|
88
|
+
ag = AgentGrid()
|
|
89
|
+
card = ag.card("ag_...")
|
|
90
|
+
keys = ag.public_keys()
|
|
91
|
+
payload = canonical(unsigned_card(card))
|
|
92
|
+
signature = card["signature"]
|
|
93
|
+
|
|
94
|
+
# base64url decode with the SDK helper, then Ed25519PublicKey.verify(...)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The platform public key (and, during rotation, the previous key) is available
|
|
98
|
+
from `GET /v1/agents/public-key`. Cards remain verifiable without a network
|
|
99
|
+
round trip.
|
|
100
|
+
|
|
101
|
+
### Statements
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
statement = ag.statement()
|
|
105
|
+
print(statement["invoice_id"], statement["total_due_usd"], statement["hard_caps"])
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Usage above included limits is metered in an immutable ledger. Overage is
|
|
109
|
+
$1 per 1,000 extra handoffs and $0.10 per extra agent per day. Every tier,
|
|
110
|
+
including Free, allows overage up to a 3x hard cap. Payments happen outside
|
|
111
|
+
the platform; AgentGrid only records external references after an operator
|
|
112
|
+
confirms them.
|
|
113
|
+
|
|
114
|
+
## Configuration
|
|
115
|
+
|
|
116
|
+
| Source | Purpose |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `AGENTGRID_API_KEY` | API key used for authenticated calls |
|
|
119
|
+
| `AGENTGRID_BASE_URL` | Override the production URL |
|
|
120
|
+
| `~/.agentgrid/credentials.json` | Locally stored key written by `agrid login` |
|
|
121
|
+
|
|
122
|
+
No key is ever printed by the SDK or CLI. Environment variables take priority
|
|
123
|
+
over the stored file.
|
|
124
|
+
|
|
125
|
+
## Errors
|
|
126
|
+
|
|
127
|
+
All API and configuration failures raise `AgentGridError` with `status` and
|
|
128
|
+
`detail` attributes.
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from agentgrid_protocol import AgentGrid, AgentGridError
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
AgentGrid().me()
|
|
135
|
+
except AgentGridError as exc:
|
|
136
|
+
print(exc.status, exc.detail)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Requirements
|
|
140
|
+
|
|
141
|
+
Python 3.10+ and `cryptography`. The SDK uses only the standard library for
|
|
142
|
+
HTTP, so it works anywhere Python runs.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
agentgrid_protocol/__init__.py
|
|
4
|
+
agentgrid_protocol/cli.py
|
|
5
|
+
agentgrid_protocol/client.py
|
|
6
|
+
agentgrid_protocol/crypto.py
|
|
7
|
+
tests/test_sdk.py
|
|
8
|
+
theoc_agentgrid_protocol.egg-info/PKG-INFO
|
|
9
|
+
theoc_agentgrid_protocol.egg-info/SOURCES.txt
|
|
10
|
+
theoc_agentgrid_protocol.egg-info/dependency_links.txt
|
|
11
|
+
theoc_agentgrid_protocol.egg-info/entry_points.txt
|
|
12
|
+
theoc_agentgrid_protocol.egg-info/requires.txt
|
|
13
|
+
theoc_agentgrid_protocol.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cryptography<51,>=42
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
agentgrid_protocol
|