theprotocol-sdk 0.6.2__tar.gz → 0.7.2__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.
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/PKG-INFO +5 -2
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/README.md +4 -1
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/pyproject.toml +1 -1
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/__init__.py +2 -1
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/exchange/client.py +18 -4
- theprotocol_sdk-0.7.2/src/theprotocol/messenger.py +256 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/mtls.py +9 -0
- theprotocol_sdk-0.7.2/tests/test_exchange_launch.py +41 -0
- theprotocol_sdk-0.7.2/tests/test_messenger.py +208 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_mtls_enroll.py +40 -0
- theprotocol_sdk-0.6.2/.gitignore +0 -88
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/LICENSE +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/examples/simple_agent.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/agent/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/agent/base.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/agent/decorators.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/agent/router.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/agent/task_store.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/agent/well_known.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/auth/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/auth/did_jwt.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/auth/jws_card.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/auth/jwt_verifier.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/authz.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/acp.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/anp/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/anp/auth.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/anp/bridge.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/anp/did_wba.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/anp/translation.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/base.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/google_a2a.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/bridges/mcp.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/client/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/client/a2a_client.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/client/credentials.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/exceptions.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/exchange/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/forge.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/guild.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/models/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/models/a2a_protocol.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/models/agent_card.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/models/v1_compat.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/payment/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/payment/authenticator.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/payment/client.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/payment/mtls_client.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/payment/verifier.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/registry/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/registry/card_verify.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/registry/cost_composition.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/transfer/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/transfer/client.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/registry/__init__.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/registry/test_card_verify.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/registry/test_cost_composition.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_agent.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_artifact_roundtrip.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_auth.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_authz.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_bridge_acp.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_bridge_anp.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_bridge_google_a2a.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_bridge_mcp.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_credentials.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_did_jwt.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_forge.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_guild.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_jws_card.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_models.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_transfer.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_v1_compat.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_verifier_reuse.py +0 -0
- {theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/tests/test_well_known.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: theprotocol-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.2
|
|
4
4
|
Summary: Build sovereign AI agents with DID identity on TheProtocol. Speaks the A2A protocol (v1.0) natively, with bridges for Google A2A, ANP, and MCP. Works with Vertex AI, AWS AgentCore, LangGraph, CrewAI.
|
|
5
5
|
Project-URL: Homepage, https://theprotocol.cloud
|
|
6
6
|
Project-URL: Documentation, https://docs.theprotocol.cloud
|
|
@@ -183,6 +183,9 @@ The private key is written `0600` into a `0700` directory, via a temp file and r
|
|
|
183
183
|
|
|
184
184
|
## Changelog
|
|
185
185
|
|
|
186
|
+
**0.7.2** (2026-09-22)
|
|
187
|
+
- AGORA words: `ExchangeClient.launch_buy` buys points at launch; `ipo_buy` still works and raises a `DeprecationWarning`. The client keeps calling the long-standing `/api/v1/exchange` paths, which every registry serves; registries from V0419 also answer the documented `/api/v1/agora` names.
|
|
188
|
+
|
|
186
189
|
**0.6.2** (2026-08-09)
|
|
187
190
|
- NEW `theprotocol.mtls.IronhandClient` — enroll for mTLS from anywhere: writes `svid.pem`/`key.pem`/`bundle.pem` (key `0600`, atomic replace) when the registry delivers inline, reports the on-host case without touching disk, and rotates via `ensure_fresh()` or a `start_auto_rotate()` background task. A settled refusal (`IronhandUnavailableError`, `IronhandPermissionError`) stops the rotation loop; transient errors are retried.
|
|
188
191
|
|
|
@@ -243,7 +246,7 @@ result = await client.call(target_url, payload)
|
|
|
243
246
|
|
|
244
247
|
## MCP Tools
|
|
245
248
|
|
|
246
|
-
For governance, staking, transfers, and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA
|
|
249
|
+
For governance, staking, transfers, and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA market; append `?mode=gateway` to browse it on demand instead of loading the full catalog.
|
|
247
250
|
|
|
248
251
|
## License
|
|
249
252
|
|
|
@@ -142,6 +142,9 @@ The private key is written `0600` into a `0700` directory, via a temp file and r
|
|
|
142
142
|
|
|
143
143
|
## Changelog
|
|
144
144
|
|
|
145
|
+
**0.7.2** (2026-09-22)
|
|
146
|
+
- AGORA words: `ExchangeClient.launch_buy` buys points at launch; `ipo_buy` still works and raises a `DeprecationWarning`. The client keeps calling the long-standing `/api/v1/exchange` paths, which every registry serves; registries from V0419 also answer the documented `/api/v1/agora` names.
|
|
147
|
+
|
|
145
148
|
**0.6.2** (2026-08-09)
|
|
146
149
|
- NEW `theprotocol.mtls.IronhandClient` — enroll for mTLS from anywhere: writes `svid.pem`/`key.pem`/`bundle.pem` (key `0600`, atomic replace) when the registry delivers inline, reports the on-host case without touching disk, and rotates via `ensure_fresh()` or a `start_auto_rotate()` background task. A settled refusal (`IronhandUnavailableError`, `IronhandPermissionError`) stops the rotation loop; transient errors are retried.
|
|
147
150
|
|
|
@@ -202,7 +205,7 @@ result = await client.call(target_url, payload)
|
|
|
202
205
|
|
|
203
206
|
## MCP Tools
|
|
204
207
|
|
|
205
|
-
For governance, staking, transfers, and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA
|
|
208
|
+
For governance, staking, transfers, and discovery, connect any MCP client (Claude Desktop, Claude Code, ...) to the registry's [MCP server](https://api.theprotocol.cloud/mcp/sse). The public tool surface spans discovery, wallet, staking, governance, the Guild, and the AGORA market; append `?mode=gateway` to browse it on demand instead of loading the full catalog.
|
|
206
209
|
|
|
207
210
|
## License
|
|
208
211
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "theprotocol-sdk"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.2"
|
|
8
8
|
description = "Build sovereign AI agents with DID identity on TheProtocol. Speaks the A2A protocol (v1.0) natively, with bridges for Google A2A, ANP, and MCP. Works with Vertex AI, AWS AgentCore, LangGraph, CrewAI."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = {text = "Apache-2.0"}
|
|
@@ -11,6 +11,7 @@ Usage:
|
|
|
11
11
|
from theprotocol.authz import AuthzClient # IRONKEY delegation + capability tokens
|
|
12
12
|
from theprotocol.registry import verify_registry_card # Registry Card EdDSA check
|
|
13
13
|
from theprotocol.mtls import IronhandClient # mTLS enrollment + SVID rotation
|
|
14
|
+
from theprotocol.messenger import MessengerClient # OurChat threads (poll/ack inbox, cards)
|
|
14
15
|
"""
|
|
15
16
|
|
|
16
|
-
__version__ = "0.
|
|
17
|
+
__version__ = "0.7.2"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"""
|
|
2
|
-
AGORA
|
|
2
|
+
AGORA Client: trade organization points on the AGORA market from agent code.
|
|
3
3
|
|
|
4
4
|
Market data is public; order/portfolio calls take the agent's JWT.
|
|
5
5
|
|
|
@@ -8,13 +8,14 @@ Market data is public; order/portfolio calls take the agent's JWT.
|
|
|
8
8
|
res = await ex.place_order(agent_jwt, "BL1F", "buy", qty=5, price="4.20")
|
|
9
9
|
await ex.cancel_order(agent_jwt, res["order_id"])
|
|
10
10
|
|
|
11
|
-
Money model (why you can trust it):
|
|
11
|
+
Money model (why you can trust it): points are registry-ledger entries; every
|
|
12
12
|
money leg settles through the venue escrow on TEG rails — buy escrow is taken
|
|
13
13
|
on placement, refunds/proceeds drain via the settlement worker. Fees come from
|
|
14
14
|
SELLER proceeds (a buy never pays more than its escrow). Supply Δ=0 by
|
|
15
15
|
construction; the venue self-checks via GET /exchange/admin/invariant.
|
|
16
16
|
"""
|
|
17
17
|
import logging
|
|
18
|
+
import warnings
|
|
18
19
|
from typing import Any, Dict, List, Optional
|
|
19
20
|
|
|
20
21
|
import httpx
|
|
@@ -23,7 +24,10 @@ logger = logging.getLogger(__name__)
|
|
|
23
24
|
|
|
24
25
|
|
|
25
26
|
class ExchangeClient:
|
|
26
|
-
"""Client for an AGORA
|
|
27
|
+
"""Client for an AGORA market (one registry hosting an order book).
|
|
28
|
+
|
|
29
|
+
The base path stays /api/v1/exchange in this release: every registry serves it, while the documented
|
|
30
|
+
/api/v1/agora names exist only on registries running V0419 or newer (the switch comes in a later release)."""
|
|
27
31
|
|
|
28
32
|
def __init__(self, registry_url: str, timeout: float = 15.0):
|
|
29
33
|
self.base = registry_url.rstrip("/") + "/api/v1/exchange"
|
|
@@ -117,8 +121,18 @@ class ExchangeClient:
|
|
|
117
121
|
r.raise_for_status()
|
|
118
122
|
return r.json()
|
|
119
123
|
|
|
120
|
-
async def
|
|
124
|
+
async def launch_buy(self, agent_jwt: str, ref: str, qty: int) -> Dict[str, Any]:
|
|
125
|
+
"""Buy points at launch: from a listing's launch allocation, at the fixed launch price.
|
|
126
|
+
|
|
127
|
+
The wire path is the long-standing `/listings/{ref}/ipo/buy`, which every registry serves; the new name
|
|
128
|
+
`/api/v1/agora/listings/{ref}/launch/buy` exists only on registries running V0419 or newer."""
|
|
121
129
|
r = await self._c().post(f"{self.base}/listings/{ref}/ipo/buy", json={"qty": qty},
|
|
122
130
|
headers=self._auth(agent_jwt))
|
|
123
131
|
r.raise_for_status()
|
|
124
132
|
return r.json()
|
|
133
|
+
|
|
134
|
+
async def ipo_buy(self, agent_jwt: str, ref: str, qty: int) -> Dict[str, Any]:
|
|
135
|
+
"""Deprecated: the earlier name of `launch_buy`. It keeps working and warns once per call site."""
|
|
136
|
+
warnings.warn("ExchangeClient.ipo_buy is deprecated; use ExchangeClient.launch_buy",
|
|
137
|
+
DeprecationWarning, stacklevel=2)
|
|
138
|
+
return await self.launch_buy(agent_jwt, ref, qty)
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Messenger Client — OurChat threads for an agent runtime (§OURSTATE-3 REACH).
|
|
3
|
+
|
|
4
|
+
Your agent can already be woken by the `chat.message.received` webhook and can
|
|
5
|
+
already reply through the dual-auth message API with its own JWT. This module
|
|
6
|
+
is the CONVENIENCE half of that: a poll/ack inbox loop for runtimes that have
|
|
7
|
+
no public URL, and typed helpers so a reply is one call instead of five.
|
|
8
|
+
|
|
9
|
+
msgr = MessengerClient("https://frame-c.theprotocol.cloud")
|
|
10
|
+
|
|
11
|
+
# A poll loop for a runtime behind NAT — no webhook endpoint required.
|
|
12
|
+
async for msg in msgr.listen(agent_jwt, interval=5.0):
|
|
13
|
+
if msg["kind"] == "text":
|
|
14
|
+
await msgr.reply(agent_jwt, msg["conversation_id"], f"heard: {msg['body']}")
|
|
15
|
+
|
|
16
|
+
# Or webhook-driven: you already have the event, just answer it.
|
|
17
|
+
await msgr.reply(agent_jwt, conv_id, "on it")
|
|
18
|
+
|
|
19
|
+
THREE THINGS THIS CLIENT WILL NOT DO, on purpose:
|
|
20
|
+
|
|
21
|
+
* It never sends money. A `service.call` / `service.result` card is written
|
|
22
|
+
ONLY by the registry's own rail (`/chat/conversations/{id}/service-call`),
|
|
23
|
+
which composes the proven `/a2a-payment/buy` loop. If your agent wants to
|
|
24
|
+
be paid, publish a priced card and let the buyer call it — an SDK that
|
|
25
|
+
could mint a receipt would make receipts worthless.
|
|
26
|
+
* It never invents a card type. The vocabulary is closed server-side; this
|
|
27
|
+
client exposes exactly the client-postable ones and lets the registry
|
|
28
|
+
refuse anything else BY NAME.
|
|
29
|
+
* It never marks something read that it did not hand you. `ack` is explicit
|
|
30
|
+
and monotonic, so a crash mid-handler replays the message instead of
|
|
31
|
+
losing it — at-least-once, which is the honest guarantee for a poll loop.
|
|
32
|
+
"""
|
|
33
|
+
import asyncio
|
|
34
|
+
import logging
|
|
35
|
+
import uuid
|
|
36
|
+
from typing import Any, AsyncIterator, Dict, List, Optional
|
|
37
|
+
|
|
38
|
+
import httpx
|
|
39
|
+
|
|
40
|
+
logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class MessengerError(RuntimeError):
|
|
44
|
+
"""Raised on a non-2xx chat response, carrying the registry's own detail."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, status_code: int, detail: Any):
|
|
47
|
+
self.status_code = status_code
|
|
48
|
+
self.detail = detail
|
|
49
|
+
super().__init__(f"messenger request failed ({status_code}): {str(detail)[:300]}")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class MessengerClient:
|
|
53
|
+
"""Client for one registry's OurChat surface.
|
|
54
|
+
|
|
55
|
+
Every method takes the JWT of the principal that should be RECORDED as the
|
|
56
|
+
speaker — the registry stamps the authenticated principal, never a claim in
|
|
57
|
+
the body, so passing your owner's developer JWT makes the owner the author
|
|
58
|
+
and passing the agent's JWT makes the agent the author. That is the whole
|
|
59
|
+
identity model, and it is why there is no `speak_as` parameter.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, registry_url: str, transport: Optional[httpx.AsyncBaseTransport] = None,
|
|
63
|
+
timeout: float = 30.0):
|
|
64
|
+
self.base = registry_url.rstrip("/")
|
|
65
|
+
self._transport = transport
|
|
66
|
+
self._timeout = timeout
|
|
67
|
+
|
|
68
|
+
# ── plumbing ────────────────────────────────────────────────────────────
|
|
69
|
+
async def _request(self, method: str, path: str, jwt: Optional[str] = None,
|
|
70
|
+
json: Optional[dict] = None, params: Optional[dict] = None) -> Any:
|
|
71
|
+
headers = {"Authorization": f"Bearer {jwt}"} if jwt else {}
|
|
72
|
+
async with httpx.AsyncClient(transport=self._transport, timeout=self._timeout) as c:
|
|
73
|
+
r = await c.request(method, f"{self.base}/api/v1/chat{path}",
|
|
74
|
+
headers=headers, json=json, params=params)
|
|
75
|
+
if r.status_code >= 400:
|
|
76
|
+
try:
|
|
77
|
+
detail = r.json().get("detail", r.text)
|
|
78
|
+
except Exception: # noqa: BLE001
|
|
79
|
+
detail = r.text
|
|
80
|
+
raise MessengerError(r.status_code, detail)
|
|
81
|
+
return r.json() if r.content else None
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def _ref() -> str:
|
|
85
|
+
"""A fresh idempotency key. Reuse one deliberately to make a retry
|
|
86
|
+
replay instead of duplicating — the schema enforces it, not luck."""
|
|
87
|
+
return str(uuid.uuid4())
|
|
88
|
+
|
|
89
|
+
# ── reading ─────────────────────────────────────────────────────────────
|
|
90
|
+
async def threads(self, jwt: str, state: str = "active", limit: int = 30) -> List[dict]:
|
|
91
|
+
"""Your threads. `state='requests'` is the strangers' lane — messages
|
|
92
|
+
there are real, but the sender is waiting on your acceptance."""
|
|
93
|
+
data = await self._request("GET", "/conversations", jwt,
|
|
94
|
+
params={"state": state, "limit": limit})
|
|
95
|
+
return data.get("conversations", [])
|
|
96
|
+
|
|
97
|
+
async def messages(self, jwt: str, conversation_id: str, before_seq: Optional[int] = None,
|
|
98
|
+
limit: int = 40) -> dict:
|
|
99
|
+
params: Dict[str, Any] = {"limit": limit}
|
|
100
|
+
if before_seq:
|
|
101
|
+
params["before_seq"] = before_seq
|
|
102
|
+
return await self._request("GET", f"/conversations/{conversation_id}/messages",
|
|
103
|
+
jwt, params=params)
|
|
104
|
+
|
|
105
|
+
async def sync(self, jwt: str, since_iso: Optional[str] = None) -> dict:
|
|
106
|
+
"""Everything in your active threads since a timestamp. The response
|
|
107
|
+
STATES its own bounds — read them; a truncated page that looks complete
|
|
108
|
+
is how a poll loop silently drops work."""
|
|
109
|
+
return await self._request("GET", "/sync", jwt,
|
|
110
|
+
params={"since": since_iso} if since_iso else None)
|
|
111
|
+
|
|
112
|
+
async def ack(self, jwt: str, conversation_id: str, seq: int) -> dict:
|
|
113
|
+
"""Acknowledge up to `seq`. Monotonic: acking an older seq is a no-op,
|
|
114
|
+
so a retry can never un-read something."""
|
|
115
|
+
return await self._request("POST", "/inbox/ack", jwt,
|
|
116
|
+
json={"conversation_id": conversation_id, "seq": seq})
|
|
117
|
+
|
|
118
|
+
async def poll_once(self, jwt: str, seen: Optional[set] = None,
|
|
119
|
+
include_requests: bool = False) -> List[dict]:
|
|
120
|
+
"""ONE polling pass: the messages addressed to you that `seen` has not
|
|
121
|
+
already returned, oldest-first. Split out of `listen` deliberately —
|
|
122
|
+
a loop with a timer inside is untestable without timers, and a probe
|
|
123
|
+
that needs a stopwatch to answer is a probe that will one day hang
|
|
124
|
+
instead of failing."""
|
|
125
|
+
out: List[dict] = []
|
|
126
|
+
lanes = ["active", "requests"] if include_requests else ["active"]
|
|
127
|
+
for lane in lanes:
|
|
128
|
+
for th in await self.threads(jwt, state=lane, limit=30):
|
|
129
|
+
cid = th.get("id")
|
|
130
|
+
unread = int(th.get("unread") or 0)
|
|
131
|
+
if not cid or unread <= 0:
|
|
132
|
+
continue
|
|
133
|
+
page = await self.messages(jwt, cid, limit=min(unread, 40))
|
|
134
|
+
for m in page.get("messages", []):
|
|
135
|
+
key = (cid, m.get("id"))
|
|
136
|
+
if seen is not None:
|
|
137
|
+
if key in seen:
|
|
138
|
+
continue
|
|
139
|
+
seen.add(key)
|
|
140
|
+
m["conversation_id"] = cid
|
|
141
|
+
out.append(m)
|
|
142
|
+
return out
|
|
143
|
+
|
|
144
|
+
async def listen(self, jwt: str, interval: float = 5.0,
|
|
145
|
+
include_requests: bool = False) -> AsyncIterator[dict]:
|
|
146
|
+
"""Poll for messages addressed to you and yield them oldest-first.
|
|
147
|
+
|
|
148
|
+
AT-LEAST-ONCE by construction: a message is yielded before it is acked,
|
|
149
|
+
and acking is YOUR call (`ack()` after your handler succeeds). A crash
|
|
150
|
+
mid-handler therefore replays rather than loses — and because every
|
|
151
|
+
send carries a `client_ref`, your own replies stay idempotent through
|
|
152
|
+
that replay.
|
|
153
|
+
"""
|
|
154
|
+
seen: set = set()
|
|
155
|
+
while True:
|
|
156
|
+
try:
|
|
157
|
+
for m in await self.poll_once(jwt, seen, include_requests):
|
|
158
|
+
yield m
|
|
159
|
+
except MessengerError as e:
|
|
160
|
+
# A poll loop that dies on one bad response is a poll loop that
|
|
161
|
+
# silently stops working. Log and keep the cadence.
|
|
162
|
+
logger.warning("messenger poll failed (%s); retrying", e)
|
|
163
|
+
except Exception as e: # noqa: BLE001
|
|
164
|
+
logger.warning("messenger poll error: %s; retrying", e)
|
|
165
|
+
if len(seen) > 5000:
|
|
166
|
+
seen = set(list(seen)[-2000:])
|
|
167
|
+
await asyncio.sleep(interval)
|
|
168
|
+
|
|
169
|
+
# ── writing (text + the CLIENT-POSTABLE cards only) ─────────────────────
|
|
170
|
+
async def open_thread(self, jwt: str, *, developer_id: Optional[int] = None,
|
|
171
|
+
handle: Optional[str] = None, agent_did: Optional[str] = None,
|
|
172
|
+
kind: str = "dm", first_message: Optional[str] = None) -> dict:
|
|
173
|
+
"""Open (or dedup-return) a thread. Address by developer id, by `@handle`
|
|
174
|
+
(§OURSTATE-3), or by an agent DID for a service thread."""
|
|
175
|
+
if agent_did:
|
|
176
|
+
target = {"ptype": "agent", "agent_did": agent_did}
|
|
177
|
+
elif handle:
|
|
178
|
+
target = {"ptype": "developer", "handle": handle}
|
|
179
|
+
elif developer_id is not None:
|
|
180
|
+
target = {"ptype": "developer", "developer_id": developer_id}
|
|
181
|
+
else:
|
|
182
|
+
raise ValueError("address the thread by developer_id, handle or agent_did")
|
|
183
|
+
body: Dict[str, Any] = {"kind": kind, "target": target}
|
|
184
|
+
if first_message:
|
|
185
|
+
body["first_message"] = {"kind": "text", "body": first_message,
|
|
186
|
+
"client_ref": self._ref()}
|
|
187
|
+
return await self._request("POST", "/conversations", jwt, json=body)
|
|
188
|
+
|
|
189
|
+
async def reply(self, jwt: str, conversation_id: str, text: str,
|
|
190
|
+
client_ref: Optional[str] = None) -> dict:
|
|
191
|
+
"""Send one text message. Pass your own `client_ref` to make a retry
|
|
192
|
+
replay the original instead of posting twice."""
|
|
193
|
+
return await self._request(
|
|
194
|
+
"POST", f"/conversations/{conversation_id}/messages", jwt,
|
|
195
|
+
json={"kind": "text", "body": text, "client_ref": client_ref or self._ref()})
|
|
196
|
+
|
|
197
|
+
async def send_card(self, jwt: str, conversation_id: str, card: dict,
|
|
198
|
+
client_ref: Optional[str] = None) -> dict:
|
|
199
|
+
"""Post a typed card. The vocabulary is CLOSED server-side: pay.request,
|
|
200
|
+
pay.receipt, agent.card and the WORK pointers are client-postable;
|
|
201
|
+
service records are written only by the registry's own rail, and an
|
|
202
|
+
unknown type is refused by name. Use the builders below."""
|
|
203
|
+
return await self._request(
|
|
204
|
+
"POST", f"/conversations/{conversation_id}/messages", jwt,
|
|
205
|
+
json={"kind": "card", "card": card, "client_ref": client_ref or self._ref()})
|
|
206
|
+
|
|
207
|
+
# ── card builders (mirrors of services/chat/cards.ts) ───────────────────
|
|
208
|
+
@staticmethod
|
|
209
|
+
def pay_request(amount: str, currency: str, memo: str = "") -> dict:
|
|
210
|
+
"""Ask to be paid. This is an ASK — it moves nothing; the payer's own
|
|
211
|
+
send door does, with their own confirmation."""
|
|
212
|
+
data: Dict[str, Any] = {"amount": str(amount), "currency": currency}
|
|
213
|
+
if memo:
|
|
214
|
+
data["memo"] = memo[:240]
|
|
215
|
+
return {"v": 1, "type": "pay.request", "data": data}
|
|
216
|
+
|
|
217
|
+
@staticmethod
|
|
218
|
+
def agent_card(did: str, name: str = "") -> dict:
|
|
219
|
+
"""Share an agent into the thread."""
|
|
220
|
+
data: Dict[str, Any] = {"did": did}
|
|
221
|
+
if name:
|
|
222
|
+
data["name"] = name[:120]
|
|
223
|
+
return {"v": 1, "type": "agent.card", "data": data}
|
|
224
|
+
|
|
225
|
+
@staticmethod
|
|
226
|
+
def work_pointer(kind: str, ref: str, title: str, amount: Optional[str] = None,
|
|
227
|
+
currency: Optional[str] = None, status: str = "") -> dict:
|
|
228
|
+
"""Point at a contract or guild order you are a party to. A POINTER:
|
|
229
|
+
awarding, delivering and settling stay on the work rail itself."""
|
|
230
|
+
if kind not in ("contract.offer", "guild.order"):
|
|
231
|
+
raise ValueError("kind must be 'contract.offer' or 'guild.order'")
|
|
232
|
+
data: Dict[str, Any] = {"ref": str(ref)[:128], "title": str(title)[:200]}
|
|
233
|
+
if amount is not None and currency:
|
|
234
|
+
data["amount"] = str(amount)
|
|
235
|
+
data["currency"] = currency
|
|
236
|
+
if status:
|
|
237
|
+
data["status"] = status[:40]
|
|
238
|
+
return {"v": 1, "type": kind, "data": data}
|
|
239
|
+
|
|
240
|
+
# ── thread state ────────────────────────────────────────────────────────
|
|
241
|
+
async def accept(self, jwt: str, conversation_id: str) -> dict:
|
|
242
|
+
"""Accept a request thread. Replying accepts it too — this is for
|
|
243
|
+
accepting without speaking yet."""
|
|
244
|
+
return await self._request("POST", f"/conversations/{conversation_id}/accept", jwt, json={})
|
|
245
|
+
|
|
246
|
+
async def decline(self, jwt: str, conversation_id: str) -> dict:
|
|
247
|
+
return await self._request("POST", f"/conversations/{conversation_id}/decline", jwt, json={})
|
|
248
|
+
|
|
249
|
+
async def leave(self, jwt: str, conversation_id: str) -> dict:
|
|
250
|
+
return await self._request("POST", f"/conversations/{conversation_id}/leave", jwt, json={})
|
|
251
|
+
|
|
252
|
+
# ── handles (§OURSTATE-3) ───────────────────────────────────────────────
|
|
253
|
+
async def profile(self, handle: str) -> dict:
|
|
254
|
+
"""The public card behind a handle. No auth: this is the page a contact
|
|
255
|
+
QR opens."""
|
|
256
|
+
return await self._request("GET", f"/handles/{handle.lstrip('@')}")
|
|
@@ -195,6 +195,15 @@ class IronhandClient:
|
|
|
195
195
|
detail = resp.text
|
|
196
196
|
if resp.status_code == 403 and "identity.mtls" in str(detail):
|
|
197
197
|
raise IronhandPermissionError(resp.status_code, detail)
|
|
198
|
+
# findings row 198 — a registry that CANNOT issue now says so with a 503 and a
|
|
199
|
+
# reason, instead of the 200 "enrolled" it used to answer while creating a SPIRE
|
|
200
|
+
# entry no agent could ever attest. That is the same condition `unavailable`
|
|
201
|
+
# describes (nothing was enrolled, nothing claims an identity), so it gets the same
|
|
202
|
+
# exception type rather than the generic one — a caller already branching on
|
|
203
|
+
# IronhandUnavailableError should not have to learn a second shape for it. The
|
|
204
|
+
# detail is passed through WHOLE: it names the cause, the fix and the doc link.
|
|
205
|
+
if resp.status_code == 503:
|
|
206
|
+
raise IronhandUnavailableError("unavailable", str(detail))
|
|
198
207
|
raise IronhandError(resp.status_code, detail)
|
|
199
208
|
|
|
200
209
|
body = resp.json()
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""§AGORAWORDS (0.7.2): ExchangeClient.launch_buy is the name; ipo_buy still works and warns. Hermetic via MockTransport."""
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from theprotocol.exchange.client import ExchangeClient
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _client(handler):
|
|
11
|
+
c = ExchangeClient("https://reg.example")
|
|
12
|
+
c._client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
|
13
|
+
return c
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.mark.asyncio
|
|
17
|
+
async def test_launch_buy_posts_the_path_every_registry_serves():
|
|
18
|
+
seen = {}
|
|
19
|
+
|
|
20
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
21
|
+
seen["url"], seen["auth"], seen["body"] = str(request.url), request.headers.get("authorization"), json.loads(request.content)
|
|
22
|
+
return httpx.Response(200, json={"purchase_id": 7, "status": "pending", "qty": 5, "amount": "5"})
|
|
23
|
+
|
|
24
|
+
c = _client(handler)
|
|
25
|
+
out = await c.launch_buy("jwt-a", "ALFW", 5)
|
|
26
|
+
await c.aclose()
|
|
27
|
+
assert seen["url"] == "https://reg.example/api/v1/exchange/listings/ALFW/ipo/buy"
|
|
28
|
+
assert seen["auth"] == "Bearer jwt-a" and seen["body"] == {"qty": 5}
|
|
29
|
+
assert out["purchase_id"] == 7
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.mark.asyncio
|
|
33
|
+
async def test_ipo_buy_is_a_deprecated_alias_with_the_same_result():
|
|
34
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
35
|
+
return httpx.Response(200, json={"purchase_id": 8, "status": "pending", "qty": 2, "amount": "2"})
|
|
36
|
+
|
|
37
|
+
c = _client(handler)
|
|
38
|
+
with pytest.warns(DeprecationWarning, match="launch_buy"):
|
|
39
|
+
out = await c.ipo_buy("jwt-a", "ALFW", 2)
|
|
40
|
+
await c.aclose()
|
|
41
|
+
assert out["purchase_id"] == 8
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Tests for theprotocol.messenger.MessengerClient (§OURSTATE-3) — hermetic
|
|
2
|
+
via MockTransport. The point of each test is a CONTRACT, not coverage: the
|
|
3
|
+
speaker is the token, the vocabulary is closed, the loop is at-least-once.
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from theprotocol.messenger import MessengerClient, MessengerError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _client_with(handler):
|
|
14
|
+
return MessengerClient("https://reg.example", transport=httpx.MockTransport(handler))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ── addressing ────────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
@pytest.mark.asyncio
|
|
20
|
+
async def test_open_thread_by_handle_sends_the_handle_not_a_guessed_id():
|
|
21
|
+
captured = {}
|
|
22
|
+
|
|
23
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
24
|
+
captured["url"] = str(request.url)
|
|
25
|
+
captured["body"] = json.loads(request.content)
|
|
26
|
+
captured["auth"] = request.headers.get("Authorization")
|
|
27
|
+
return httpx.Response(201, json={"conversation_id": "c1", "created": True})
|
|
28
|
+
|
|
29
|
+
out = await _client_with(handler).open_thread("dev.jwt", handle="@ruffa",
|
|
30
|
+
first_message="hello")
|
|
31
|
+
assert out["conversation_id"] == "c1"
|
|
32
|
+
assert captured["url"].endswith("/api/v1/chat/conversations")
|
|
33
|
+
assert captured["body"]["target"] == {"ptype": "developer", "handle": "@ruffa"}
|
|
34
|
+
assert captured["auth"] == "Bearer dev.jwt"
|
|
35
|
+
# A first message always carries an idempotency key, even when the caller
|
|
36
|
+
# did not think about retries.
|
|
37
|
+
assert captured["body"]["first_message"]["client_ref"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@pytest.mark.asyncio
|
|
41
|
+
async def test_open_thread_requires_an_address():
|
|
42
|
+
with pytest.raises(ValueError):
|
|
43
|
+
await _client_with(lambda r: httpx.Response(200, json={})).open_thread("jwt")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.mark.asyncio
|
|
47
|
+
async def test_agent_did_opens_a_service_thread_target():
|
|
48
|
+
captured = {}
|
|
49
|
+
|
|
50
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
51
|
+
captured["body"] = json.loads(request.content)
|
|
52
|
+
return httpx.Response(201, json={"conversation_id": "c2"})
|
|
53
|
+
|
|
54
|
+
await _client_with(handler).open_thread("jwt", agent_did="did:theprotocol:x",
|
|
55
|
+
kind="agent_service")
|
|
56
|
+
assert captured["body"]["kind"] == "agent_service"
|
|
57
|
+
assert captured["body"]["target"]["agent_did"] == "did:theprotocol:x"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ── the speaker IS the token ──────────────────────────────────────────────────
|
|
61
|
+
|
|
62
|
+
@pytest.mark.asyncio
|
|
63
|
+
async def test_reply_records_the_token_holder_and_never_a_claimed_author():
|
|
64
|
+
captured = {}
|
|
65
|
+
|
|
66
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
67
|
+
captured["auth"] = request.headers.get("Authorization")
|
|
68
|
+
captured["body"] = json.loads(request.content)
|
|
69
|
+
return httpx.Response(201, json={"message": {"seq": 4}})
|
|
70
|
+
|
|
71
|
+
await _client_with(handler).reply("agent.jwt", "c1", "on it")
|
|
72
|
+
assert captured["auth"] == "Bearer agent.jwt"
|
|
73
|
+
# No speak_as / sender / author field exists to be forged.
|
|
74
|
+
assert set(captured["body"]) == {"kind", "body", "client_ref"}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@pytest.mark.asyncio
|
|
78
|
+
async def test_reply_honours_a_caller_supplied_client_ref_for_replay():
|
|
79
|
+
captured = {}
|
|
80
|
+
|
|
81
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
82
|
+
captured["ref"] = json.loads(request.content)["client_ref"]
|
|
83
|
+
return httpx.Response(201, json={"message": {}})
|
|
84
|
+
|
|
85
|
+
await _client_with(handler).reply("jwt", "c1", "hi", client_ref="fixed-ref-123")
|
|
86
|
+
assert captured["ref"] == "fixed-ref-123"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ── the card vocabulary is closed, and the builders mirror it ────────────────
|
|
90
|
+
|
|
91
|
+
def test_pay_request_builder_shape():
|
|
92
|
+
card = MessengerClient.pay_request("12.5", "BVT", memo="the invoice")
|
|
93
|
+
assert card == {"v": 1, "type": "pay.request",
|
|
94
|
+
"data": {"amount": "12.5", "currency": "BVT", "memo": "the invoice"}}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_work_pointer_refuses_a_type_outside_the_vocabulary():
|
|
98
|
+
with pytest.raises(ValueError):
|
|
99
|
+
MessengerClient.work_pointer("service.result", "r", "t")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_work_pointer_omits_an_amount_without_a_currency():
|
|
103
|
+
# Never a bare number: an amount with no unit is the §FOREIGNACT bug.
|
|
104
|
+
card = MessengerClient.work_pointer("guild.order", "o1", "Translate", amount="5")
|
|
105
|
+
assert "amount" not in card["data"]
|
|
106
|
+
card2 = MessengerClient.work_pointer("guild.order", "o1", "Translate", amount="5", currency="BVT")
|
|
107
|
+
assert card2["data"]["amount"] == "5" and card2["data"]["currency"] == "BVT"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_there_is_no_builder_for_a_service_record():
|
|
111
|
+
# Receipts are written by the registry's rail. An SDK that could mint one
|
|
112
|
+
# would make every receipt worthless.
|
|
113
|
+
assert not hasattr(MessengerClient, "service_result")
|
|
114
|
+
assert not hasattr(MessengerClient, "pay_receipt_signed")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# ── the ack half ──────────────────────────────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
@pytest.mark.asyncio
|
|
120
|
+
async def test_ack_posts_the_conversation_and_seq():
|
|
121
|
+
captured = {}
|
|
122
|
+
|
|
123
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
124
|
+
captured["url"] = str(request.url)
|
|
125
|
+
captured["body"] = json.loads(request.content)
|
|
126
|
+
return httpx.Response(200, json={"ok": True})
|
|
127
|
+
|
|
128
|
+
await _client_with(handler).ack("jwt", "c9", 42)
|
|
129
|
+
assert captured["url"].endswith("/api/v1/chat/inbox/ack")
|
|
130
|
+
assert captured["body"] == {"conversation_id": "c9", "seq": 42}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# ── errors carry the registry's own words ────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
@pytest.mark.asyncio
|
|
136
|
+
async def test_error_carries_status_and_detail():
|
|
137
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
138
|
+
return httpx.Response(403, json={"detail": "this room is announce-only"})
|
|
139
|
+
|
|
140
|
+
with pytest.raises(MessengerError) as e:
|
|
141
|
+
await _client_with(handler).reply("jwt", "c1", "hi")
|
|
142
|
+
assert e.value.status_code == 403
|
|
143
|
+
assert "announce-only" in str(e.value.detail)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ── the poll loop is at-least-once, and survives a bad response ──────────────
|
|
147
|
+
|
|
148
|
+
@pytest.mark.asyncio
|
|
149
|
+
async def test_poll_once_yields_unread_and_dedups_across_passes():
|
|
150
|
+
"""The loop's contract without a stopwatch: `poll_once` is the testable
|
|
151
|
+
seam, so 'yielded exactly once' is a definite answer rather than a timeout.
|
|
152
|
+
(The first cut of this test drove `listen` and hung — an `async for … break`
|
|
153
|
+
only re-checks its condition when the loop YIELDS, and this loop dedups.)"""
|
|
154
|
+
calls = {"threads": 0}
|
|
155
|
+
|
|
156
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
157
|
+
path = request.url.path
|
|
158
|
+
if path.endswith("/conversations"):
|
|
159
|
+
calls["threads"] += 1
|
|
160
|
+
return httpx.Response(200, json={"conversations": [{"id": "c1", "unread": 1}]})
|
|
161
|
+
if "/messages" in path:
|
|
162
|
+
return httpx.Response(200, json={"messages": [
|
|
163
|
+
{"id": "m1", "seq": 1, "kind": "text", "body": "hello"}]})
|
|
164
|
+
return httpx.Response(404, json={})
|
|
165
|
+
|
|
166
|
+
msgr = _client_with(handler)
|
|
167
|
+
seen: set = set()
|
|
168
|
+
first = await msgr.poll_once("jwt", seen)
|
|
169
|
+
assert len(first) == 1 and first[0]["conversation_id"] == "c1" and first[0]["body"] == "hello"
|
|
170
|
+
second = await msgr.poll_once("jwt", seen)
|
|
171
|
+
assert second == [] # the SAME message is never handed over twice
|
|
172
|
+
assert calls["threads"] == 2 # …and the loop really did poll again
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@pytest.mark.asyncio
|
|
176
|
+
async def test_poll_once_without_a_seen_set_replays_everything():
|
|
177
|
+
"""At-least-once made explicit: a caller that keeps no memory (a fresh
|
|
178
|
+
process after a crash) gets the message again rather than losing it."""
|
|
179
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
180
|
+
if request.url.path.endswith("/conversations"):
|
|
181
|
+
return httpx.Response(200, json={"conversations": [{"id": "c1", "unread": 1}]})
|
|
182
|
+
return httpx.Response(200, json={"messages": [{"id": "m1", "seq": 1, "kind": "text", "body": "hi"}]})
|
|
183
|
+
|
|
184
|
+
msgr = _client_with(handler)
|
|
185
|
+
assert len(await msgr.poll_once("jwt")) == 1
|
|
186
|
+
assert len(await msgr.poll_once("jwt")) == 1
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@pytest.mark.asyncio
|
|
190
|
+
async def test_poll_once_skips_threads_with_nothing_unread():
|
|
191
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
192
|
+
if request.url.path.endswith("/conversations"):
|
|
193
|
+
return httpx.Response(200, json={"conversations": [
|
|
194
|
+
{"id": "c1", "unread": 0}, {"id": "c2"}]})
|
|
195
|
+
raise AssertionError("must not fetch messages for a read thread")
|
|
196
|
+
|
|
197
|
+
assert await _client_with(handler).poll_once("jwt", set()) == []
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@pytest.mark.asyncio
|
|
201
|
+
async def test_a_failing_poll_raises_to_the_caller_but_listen_survives_it():
|
|
202
|
+
"""`poll_once` is honest (it raises); `listen` is durable (it logs and keeps
|
|
203
|
+
the cadence). Both properties matter, and they belong to different layers."""
|
|
204
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
205
|
+
return httpx.Response(500, json={"detail": "boom"})
|
|
206
|
+
|
|
207
|
+
with pytest.raises(MessengerError):
|
|
208
|
+
await _client_with(handler).poll_once("jwt", set())
|
|
@@ -268,3 +268,43 @@ async def test_paths_match_what_mtls_agent_client_reads(tmp_path):
|
|
|
268
268
|
|
|
269
269
|
def test_seconds_remaining_handles_absent_expiry():
|
|
270
270
|
assert Enrollment(delivery="inline", status="enrolled").seconds_remaining() is None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# ── findings row 198 — a registry that cannot issue says so, and the SDK classifies it ──
|
|
274
|
+
|
|
275
|
+
@pytest.mark.asyncio
|
|
276
|
+
async def test_a_503_refusal_is_an_unavailable_not_a_generic_error():
|
|
277
|
+
"""The registry used to answer 200 "enrolled" while creating a SPIRE entry no agent could
|
|
278
|
+
ever attest. It now refuses with 503 and a reason. That is the same CONDITION `unavailable`
|
|
279
|
+
already described — nothing enrolled, nothing claiming an identity — so a caller already
|
|
280
|
+
branching on IronhandUnavailableError must not have to learn a second shape for it."""
|
|
281
|
+
detail = ("The SPIRE agent node chosen to parent this identity (4605f286…) is not one of "
|
|
282
|
+
"this frame's 3 live agent node(s) ... How mTLS identities are issued: "
|
|
283
|
+
"https://docs.theprotocol.cloud/learn/security")
|
|
284
|
+
|
|
285
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
286
|
+
return httpx.Response(503, json={"detail": detail})
|
|
287
|
+
|
|
288
|
+
client = IronhandClient(registry_url="https://eu.example",
|
|
289
|
+
transport=httpx.MockTransport(handler))
|
|
290
|
+
with pytest.raises(IronhandUnavailableError) as e:
|
|
291
|
+
await client.enroll("agent-jwt")
|
|
292
|
+
assert e.value.delivery == "unavailable"
|
|
293
|
+
# the reason and the link must survive WHOLE — a truncated refusal is how the caller ends
|
|
294
|
+
# up guessing, which is the entire failure this row is about
|
|
295
|
+
assert "live agent node" in str(e.value)
|
|
296
|
+
assert "docs.theprotocol.cloud/learn/security" in str(e.value)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@pytest.mark.asyncio
|
|
300
|
+
async def test_other_non_2xx_are_still_generic_errors():
|
|
301
|
+
"""The control: only 503 changes shape. A 500 must stay an IronhandError, or this mapping
|
|
302
|
+
would be swallowing failures it does not understand."""
|
|
303
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
304
|
+
return httpx.Response(500, json={"detail": "boom"})
|
|
305
|
+
|
|
306
|
+
client = IronhandClient(registry_url="https://eu.example",
|
|
307
|
+
transport=httpx.MockTransport(handler))
|
|
308
|
+
with pytest.raises(IronhandError) as e:
|
|
309
|
+
await client.enroll("agent-jwt")
|
|
310
|
+
assert not isinstance(e.value, IronhandUnavailableError)
|
theprotocol_sdk-0.6.2/.gitignore
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
# TheProtocol — Root .gitignore
|
|
2
|
-
# Created: 2026-03-09 (§4.1 Credentials Rotation)
|
|
3
|
-
|
|
4
|
-
# !! NEVER COMMIT SECRETS / LOCAL CONFIG !!
|
|
5
|
-
# All env files except *.example templates. Covers .env, .env.production,
|
|
6
|
-
# .env.frame-b, .env.frame-c, .env.operator, .env.docker, and nested
|
|
7
|
-
# AgentVault/.../.env — while keeping the committed *.env.example templates.
|
|
8
|
-
.env
|
|
9
|
-
.env.*
|
|
10
|
-
!.env.example
|
|
11
|
-
# Local agent / MCP config — these carry live API keys
|
|
12
|
-
.mcp.json
|
|
13
|
-
.claude/
|
|
14
|
-
|
|
15
|
-
# Session logs (operational, not source)
|
|
16
|
-
sessionlogs2026/
|
|
17
|
-
|
|
18
|
-
# Debug/runtime artifacts
|
|
19
|
-
logs/
|
|
20
|
-
*.log
|
|
21
|
-
APEX_PREDATOR_JOBS.log
|
|
22
|
-
|
|
23
|
-
# Node
|
|
24
|
-
node_modules/
|
|
25
|
-
|
|
26
|
-
# Python
|
|
27
|
-
__pycache__/
|
|
28
|
-
*.pyc
|
|
29
|
-
*.pyo
|
|
30
|
-
*.pyd
|
|
31
|
-
.venv/
|
|
32
|
-
*.egg-info/
|
|
33
|
-
dist/
|
|
34
|
-
build/
|
|
35
|
-
|
|
36
|
-
# OS
|
|
37
|
-
.DS_Store
|
|
38
|
-
Thumbs.db
|
|
39
|
-
|
|
40
|
-
# Backups / snapshots — carry stale secrets + bloat
|
|
41
|
-
# (e.g. *.bak-pre-*, PRODUCTION_DOCS.bak-*, CLAUDE.md.bak-*, main.py.bak-*)
|
|
42
|
-
*.bak*
|
|
43
|
-
*.pre-*
|
|
44
|
-
|
|
45
|
-
# §2026-06-29 OSS secrets scrub (#153) — internal AI-operational docs + credential
|
|
46
|
-
# references that carry live secrets and MUST NOT ship to a public repo. These are
|
|
47
|
-
# operator/agent briefings, not platform source.
|
|
48
|
-
CLAUDE.md
|
|
49
|
-
CLAUDE_ADMIN.md
|
|
50
|
-
MY_APEX_PREDATOR_TOOLING.md
|
|
51
|
-
PRODUCTION_DOCS/CREDENTIALS_REFERENCE.md
|
|
52
|
-
# Sim/dev credential blobs
|
|
53
|
-
scripts/sim_credentials.json
|
|
54
|
-
**/*credentials*.json
|
|
55
|
-
|
|
56
|
-
# Throwaway FE screenshot/diag scripts (scratch, carry prod creds)
|
|
57
|
-
AgentVault/agentvault_registry/src/agentvault_registry/static/new_registry_frontend/shot_*.mjs
|
|
58
|
-
AgentVault/agentvault_registry/src/agentvault_registry/static/new_registry_frontend/diag_*.mjs
|
|
59
|
-
AgentVault/agentvault_registry/src/agentvault_registry/static/new_registry_frontend/gate_*.mjs
|
|
60
|
-
|
|
61
|
-
# --- 2026-08-05 §FORGEJO migration: runtime data, generated artifacts, secret carriers ---
|
|
62
|
-
# Live bind-mounted container state (TheAuditor/data alone is 4.7G)
|
|
63
|
-
Agents/*/data/
|
|
64
|
-
Agents/*/logs/
|
|
65
|
-
Agents/*/circuits/
|
|
66
|
-
bundle-storage*/
|
|
67
|
-
# Generated release artifacts (operator-cli tarballs) + build output
|
|
68
|
-
dist/
|
|
69
|
-
docs-site/.vitepress/cache/
|
|
70
|
-
docs-site/.vitepress/dist/
|
|
71
|
-
# Backups carry copies of env files = secrets
|
|
72
|
-
backups/
|
|
73
|
-
*.bak*
|
|
74
|
-
# Secret carriers
|
|
75
|
-
docker-certs/
|
|
76
|
-
private/
|
|
77
|
-
*credentials*.json
|
|
78
|
-
*.secret.txt
|
|
79
|
-
|
|
80
|
-
# --- 2026-08-05 §FORGEJO hygiene pass 2: key material + credential notes never enter git ---
|
|
81
|
-
*.key
|
|
82
|
-
*.pem
|
|
83
|
-
*htpasswd*
|
|
84
|
-
*[Cc]redentials.md
|
|
85
|
-
scripts/sim_credentials.md
|
|
86
|
-
# MCP bridge JS with embedded per-registry API keys (operational config, not source)
|
|
87
|
-
mcp-theprotocol-b-bridge.js
|
|
88
|
-
mcp-theprotocol-admin-b-bridge.js
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{theprotocol_sdk-0.6.2 → theprotocol_sdk-0.7.2}/src/theprotocol/registry/cost_composition.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|