p2a-sdk 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- p2a_sdk/__init__.py +22 -0
- p2a_sdk/agent.py +546 -0
- p2a_sdk/clock.py +39 -0
- p2a_sdk/errors.py +70 -0
- p2a_sdk/sse.py +40 -0
- p2a_sdk/tools.py +52 -0
- p2a_sdk/transport.py +229 -0
- p2a_sdk-0.1.0.dist-info/METADATA +117 -0
- p2a_sdk-0.1.0.dist-info/RECORD +11 -0
- p2a_sdk-0.1.0.dist-info/WHEEL +4 -0
- p2a_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
p2a_sdk/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from p2a_sdk.agent import Context, Directive, P2AAgent, Request
|
|
2
|
+
from p2a_sdk.errors import AuthError, ConfirmationRequired, ConnectionDeclined, P2AError, RateLimited, redact
|
|
3
|
+
from p2a_sdk.sse import SseParser
|
|
4
|
+
from p2a_sdk.tools import define_tool, run_tool, to_anthropic_tools, to_openai_tools
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"AuthError",
|
|
8
|
+
"ConfirmationRequired",
|
|
9
|
+
"ConnectionDeclined",
|
|
10
|
+
"Context",
|
|
11
|
+
"Directive",
|
|
12
|
+
"P2AAgent",
|
|
13
|
+
"P2AError",
|
|
14
|
+
"RateLimited",
|
|
15
|
+
"Request",
|
|
16
|
+
"SseParser",
|
|
17
|
+
"define_tool",
|
|
18
|
+
"redact",
|
|
19
|
+
"run_tool",
|
|
20
|
+
"to_anthropic_tools",
|
|
21
|
+
"to_openai_tools",
|
|
22
|
+
]
|
p2a_sdk/agent.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import inspect
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, Awaitable, Callable
|
|
8
|
+
from uuid import uuid4
|
|
9
|
+
|
|
10
|
+
from p2a_sdk.clock import Clock, SystemClock, backoff_ms
|
|
11
|
+
from p2a_sdk.errors import AuthError, P2AError
|
|
12
|
+
from p2a_sdk.transport import Transport
|
|
13
|
+
|
|
14
|
+
LEASE_SECONDS = 300
|
|
15
|
+
CUSTOMER_TEXT = "A person from Acme will follow up here."
|
|
16
|
+
FAILED_TEXT = "Sorry, something went wrong."
|
|
17
|
+
REQUEST_NAMES = ["aweb.request.created"]
|
|
18
|
+
SIDE_NAMES = ["aweb.reply.received", "aweb.connection.requested", "aweb.connection.updated"]
|
|
19
|
+
ALL_NAMES = [*REQUEST_NAMES, *SIDE_NAMES]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Directive:
|
|
23
|
+
def __init__(self, outcome: str, result: dict[str, Any]) -> None:
|
|
24
|
+
self.outcome = outcome
|
|
25
|
+
self.result = result
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Request:
|
|
30
|
+
request_id: str
|
|
31
|
+
text: str
|
|
32
|
+
sender: dict[str, str | None]
|
|
33
|
+
same_owner: bool
|
|
34
|
+
context_id: str | None = None
|
|
35
|
+
brief: Any = None
|
|
36
|
+
event_id: str | None = None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Context:
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
agent: P2AAgent,
|
|
43
|
+
request_id: str,
|
|
44
|
+
attempt_id: str,
|
|
45
|
+
stop: asyncio.Event,
|
|
46
|
+
sender_did: str | None,
|
|
47
|
+
) -> None:
|
|
48
|
+
self.signal = stop
|
|
49
|
+
self._agent = agent
|
|
50
|
+
self._request_id = request_id
|
|
51
|
+
self._attempt_id = attempt_id
|
|
52
|
+
self._sender_did = sender_did
|
|
53
|
+
self._sender: dict[str, Any] | None = None
|
|
54
|
+
|
|
55
|
+
async def progress(self, note: str = "") -> None:
|
|
56
|
+
args: dict[str, Any] = {
|
|
57
|
+
"request_id": self._request_id,
|
|
58
|
+
"attempt_id": self._attempt_id,
|
|
59
|
+
"state": "working",
|
|
60
|
+
}
|
|
61
|
+
if note:
|
|
62
|
+
args["note"] = note
|
|
63
|
+
await self._agent.transport.call_tool("p2a_progress", args, True)
|
|
64
|
+
|
|
65
|
+
async def brief(self, scope: str = "", scope_kind: str = "", scope_id: str = "") -> dict[str, Any]:
|
|
66
|
+
return await self._agent.transport.call_tool(
|
|
67
|
+
"p2a_brief_get",
|
|
68
|
+
{"scope": scope, "scope_kind": scope_kind, "scope_id": scope_id},
|
|
69
|
+
True,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
async def sender(self) -> dict[str, Any]:
|
|
73
|
+
if self._sender is not None:
|
|
74
|
+
return self._sender
|
|
75
|
+
if not self._sender_did:
|
|
76
|
+
self._sender = {}
|
|
77
|
+
return self._sender
|
|
78
|
+
card = await self._agent.transport.call_tool(
|
|
79
|
+
"p2a_resolve_agent",
|
|
80
|
+
{"target": self._sender_did},
|
|
81
|
+
True,
|
|
82
|
+
)
|
|
83
|
+
self._sender = card
|
|
84
|
+
return card
|
|
85
|
+
|
|
86
|
+
def escalate(self, question: str, customer_text: str | None = None) -> Directive:
|
|
87
|
+
return Directive(
|
|
88
|
+
"needs_approval",
|
|
89
|
+
{"text": question, "customer_text": customer_text or CUSTOMER_TEXT},
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def ask_customer(self, text: str) -> Directive:
|
|
93
|
+
return Directive("input_required", {"text": text})
|
|
94
|
+
|
|
95
|
+
def plan(self, title: str, items: list[Any]) -> Directive:
|
|
96
|
+
return Directive("completed", {"kind": "plan", "title": title, "items": items})
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class P2AAgent:
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
token: str | None = None,
|
|
103
|
+
url: str | None = None,
|
|
104
|
+
*,
|
|
105
|
+
logger: Any = None,
|
|
106
|
+
max_concurrent: int = 4,
|
|
107
|
+
clock: Clock | None = None,
|
|
108
|
+
client: Any = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
resolved_token = token if token is not None else os.environ.get("P2A_TOKEN", "")
|
|
111
|
+
resolved_url = url if url is not None else os.environ.get("P2A_URL", "")
|
|
112
|
+
if not resolved_token or not resolved_url:
|
|
113
|
+
raise P2AError("missing_config", message="Set P2A_TOKEN and P2A_URL")
|
|
114
|
+
self.clock = clock or SystemClock()
|
|
115
|
+
self.logger = logger
|
|
116
|
+
self.max_concurrent = max_concurrent
|
|
117
|
+
self.transport = Transport(resolved_token, resolved_url, client=client, clock=self.clock)
|
|
118
|
+
self._on_request: Callable[..., Any] | None = None
|
|
119
|
+
self._on_message: Callable[..., Any] | None = None
|
|
120
|
+
self._on_outcome: Callable[..., Any] | None = None
|
|
121
|
+
self._on_reply: Callable[..., Any] | None = None
|
|
122
|
+
self._on_connection: Callable[..., Any] | None = None
|
|
123
|
+
self._seen: set[str] = set()
|
|
124
|
+
|
|
125
|
+
async def aclose(self) -> None:
|
|
126
|
+
await self.transport.aclose()
|
|
127
|
+
|
|
128
|
+
def on_request(self, handler: Callable[..., Any] | None = None):
|
|
129
|
+
def register(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
130
|
+
self._on_request = fn
|
|
131
|
+
return fn
|
|
132
|
+
|
|
133
|
+
if handler is None:
|
|
134
|
+
return register
|
|
135
|
+
return register(handler)
|
|
136
|
+
|
|
137
|
+
def on_message(self, handler: Callable[..., Any]) -> None:
|
|
138
|
+
self._on_message = handler
|
|
139
|
+
|
|
140
|
+
def on_outcome(self, handler: Callable[..., Any]) -> None:
|
|
141
|
+
self._on_outcome = handler
|
|
142
|
+
|
|
143
|
+
def on_reply(self, handler: Callable[..., Any]) -> None:
|
|
144
|
+
self._on_reply = handler
|
|
145
|
+
|
|
146
|
+
def on_connection_request(self, handler: Callable[..., Any]) -> None:
|
|
147
|
+
"""Default is no handler, which does nothing. The handler decides whether to accept."""
|
|
148
|
+
self._on_connection = handler
|
|
149
|
+
|
|
150
|
+
async def respond_connection(self, link_id: str, action: str) -> dict[str, Any]:
|
|
151
|
+
"""Accept, decline, or block. This call is the confirmation, so confirm is true."""
|
|
152
|
+
if action not in {"accept", "decline", "block"}:
|
|
153
|
+
raise P2AError("invalid_action", message="invalid_action")
|
|
154
|
+
return await self.transport.call_tool(
|
|
155
|
+
"p2a_respond_connection",
|
|
156
|
+
{"link_id": link_id, "action": action, "confirm": True},
|
|
157
|
+
False,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
async def send(
|
|
161
|
+
self,
|
|
162
|
+
to: str,
|
|
163
|
+
text: str,
|
|
164
|
+
*,
|
|
165
|
+
idempotency_key: str | None = None,
|
|
166
|
+
deadline_seconds: int | None = None,
|
|
167
|
+
wait: int = 0,
|
|
168
|
+
) -> dict[str, Any]:
|
|
169
|
+
args: dict[str, Any] = {
|
|
170
|
+
"to": to,
|
|
171
|
+
"text": text,
|
|
172
|
+
"idempotency_key": idempotency_key or str(uuid4()),
|
|
173
|
+
"wait_seconds": wait,
|
|
174
|
+
}
|
|
175
|
+
if deadline_seconds is not None:
|
|
176
|
+
args["deadline_seconds"] = deadline_seconds
|
|
177
|
+
payload = await self.transport.call_tool("p2a_send_message", args, False)
|
|
178
|
+
return _send_result(payload)
|
|
179
|
+
|
|
180
|
+
async def wait_for_reply(self, request_id: str, *, timeout: int | None = None) -> dict[str, Any]:
|
|
181
|
+
args: dict[str, Any] = {"request_id": request_id}
|
|
182
|
+
if timeout is not None:
|
|
183
|
+
args["wait_seconds"] = timeout
|
|
184
|
+
payload = await self.transport.call_tool("p2a_wait_for_reply", args, False)
|
|
185
|
+
return _send_result(payload)
|
|
186
|
+
|
|
187
|
+
async def listen(self, mode: str = "stream", stop: asyncio.Event | None = None) -> None:
|
|
188
|
+
signal = stop or asyncio.Event()
|
|
189
|
+
# Handshake only. The server marks the runtime connected on the first
|
|
190
|
+
# tools/call or events feed read, not on initialize.
|
|
191
|
+
await self.transport.initialize()
|
|
192
|
+
if signal.is_set():
|
|
193
|
+
return
|
|
194
|
+
await self._drain_inbox()
|
|
195
|
+
if signal.is_set():
|
|
196
|
+
return
|
|
197
|
+
if mode == "poll":
|
|
198
|
+
await self._poll_loop(ALL_NAMES, signal)
|
|
199
|
+
return
|
|
200
|
+
outcome = await self._stream_with_side(signal)
|
|
201
|
+
if outcome == "fallback" and not signal.is_set():
|
|
202
|
+
await self._poll_loop(ALL_NAMES, signal)
|
|
203
|
+
|
|
204
|
+
async def _drain_inbox(self) -> None:
|
|
205
|
+
inbox = await self.transport.call_tool("p2a_check_new", {}, True)
|
|
206
|
+
pending = inbox.get("pending_requests") if isinstance(inbox.get("pending_requests"), list) else []
|
|
207
|
+
replies = inbox.get("unread_replies") if isinstance(inbox.get("unread_replies"), list) else []
|
|
208
|
+
connections = inbox.get("connection_requests") if isinstance(inbox.get("connection_requests"), list) else []
|
|
209
|
+
events = []
|
|
210
|
+
for item in pending:
|
|
211
|
+
record = item if isinstance(item, dict) else {}
|
|
212
|
+
if record.get("kind") == "outcome":
|
|
213
|
+
events.append(
|
|
214
|
+
{
|
|
215
|
+
"name": "aweb.request.created",
|
|
216
|
+
"data": {
|
|
217
|
+
"request_id": record.get("request_id"),
|
|
218
|
+
"kind": "outcome",
|
|
219
|
+
"parent_request_id": record.get("parent_request_id"),
|
|
220
|
+
},
|
|
221
|
+
}
|
|
222
|
+
)
|
|
223
|
+
else:
|
|
224
|
+
events.append(
|
|
225
|
+
{
|
|
226
|
+
"name": "aweb.request.created",
|
|
227
|
+
"data": {
|
|
228
|
+
"request_id": record.get("request_id"),
|
|
229
|
+
"sender": record.get("from"),
|
|
230
|
+
"same_owner": record.get("same_owner"),
|
|
231
|
+
"kind": record.get("kind"),
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
)
|
|
235
|
+
await self._each(events)
|
|
236
|
+
for item in replies:
|
|
237
|
+
record = item if isinstance(item, dict) else {}
|
|
238
|
+
await self._dispatch_reply(
|
|
239
|
+
{
|
|
240
|
+
"request_id": record.get("request_id") if isinstance(record.get("request_id"), str) else None,
|
|
241
|
+
"summary": record.get("summary") if isinstance(record.get("summary"), str) else None,
|
|
242
|
+
}
|
|
243
|
+
)
|
|
244
|
+
for item in connections:
|
|
245
|
+
await self._dispatch_connection(item if isinstance(item, dict) else {})
|
|
246
|
+
|
|
247
|
+
async def _poll_loop(self, names: list[str], stop: asyncio.Event) -> None:
|
|
248
|
+
cursors: dict[str, str] = {}
|
|
249
|
+
while not stop.is_set():
|
|
250
|
+
wait = 25_000
|
|
251
|
+
more = False
|
|
252
|
+
for name in names:
|
|
253
|
+
if stop.is_set():
|
|
254
|
+
return
|
|
255
|
+
page = await self.transport.poll(name, cursors.get(name))
|
|
256
|
+
if isinstance(page.get("cursor"), str):
|
|
257
|
+
cursors[name] = page["cursor"]
|
|
258
|
+
if isinstance(page.get("nextPollMs"), (int, float)):
|
|
259
|
+
wait = min(wait, page["nextPollMs"])
|
|
260
|
+
if page.get("hasMore") is True:
|
|
261
|
+
more = True
|
|
262
|
+
await self._each(page.get("events") or [])
|
|
263
|
+
if stop.is_set():
|
|
264
|
+
return
|
|
265
|
+
if not more:
|
|
266
|
+
await self.clock.sleep(wait, stop)
|
|
267
|
+
|
|
268
|
+
async def _stream_with_side(self, stop: asyncio.Event) -> str:
|
|
269
|
+
side = asyncio.Event()
|
|
270
|
+
|
|
271
|
+
async def watch() -> None:
|
|
272
|
+
await stop.wait()
|
|
273
|
+
side.set()
|
|
274
|
+
|
|
275
|
+
watcher = asyncio.create_task(watch())
|
|
276
|
+
polling = asyncio.create_task(self._poll_loop(SIDE_NAMES, side))
|
|
277
|
+
try:
|
|
278
|
+
return await self._stream_loop(stop)
|
|
279
|
+
finally:
|
|
280
|
+
side.set()
|
|
281
|
+
watcher.cancel()
|
|
282
|
+
await polling
|
|
283
|
+
|
|
284
|
+
async def _stream_loop(self, stop: asyncio.Event) -> str:
|
|
285
|
+
failures = 0
|
|
286
|
+
cursor = None
|
|
287
|
+
while not stop.is_set():
|
|
288
|
+
try:
|
|
289
|
+
async for note in self.transport.stream("aweb.request.created", cursor, stop):
|
|
290
|
+
if stop.is_set():
|
|
291
|
+
return "stopped"
|
|
292
|
+
failures = 0
|
|
293
|
+
if note.get("cursor"):
|
|
294
|
+
cursor = note["cursor"]
|
|
295
|
+
if note.get("event"):
|
|
296
|
+
await self._accept(note["event"])
|
|
297
|
+
if stop.is_set():
|
|
298
|
+
return "stopped"
|
|
299
|
+
failures += 1
|
|
300
|
+
except AuthError:
|
|
301
|
+
raise
|
|
302
|
+
except Exception as err:
|
|
303
|
+
if stop.is_set() or _is_abort(err):
|
|
304
|
+
return "stopped"
|
|
305
|
+
failures += 1
|
|
306
|
+
if failures >= 3:
|
|
307
|
+
return "fallback"
|
|
308
|
+
await self.clock.sleep(backoff_ms(failures, self.clock.random()), stop)
|
|
309
|
+
return "stopped"
|
|
310
|
+
|
|
311
|
+
async def _each(self, events: list[dict[str, Any]]) -> None:
|
|
312
|
+
queue = list(events)
|
|
313
|
+
|
|
314
|
+
async def worker() -> None:
|
|
315
|
+
while queue:
|
|
316
|
+
event = queue.pop(0)
|
|
317
|
+
await self._accept(event)
|
|
318
|
+
|
|
319
|
+
count = min(self.max_concurrent, len(queue))
|
|
320
|
+
if count:
|
|
321
|
+
await asyncio.gather(*(worker() for _ in range(count)))
|
|
322
|
+
|
|
323
|
+
async def _accept(self, event: dict[str, Any]) -> None:
|
|
324
|
+
name = event.get("name") or ""
|
|
325
|
+
data = event.get("data") if isinstance(event.get("data"), dict) else {}
|
|
326
|
+
event_id = event.get("eventId") if isinstance(event.get("eventId"), str) else None
|
|
327
|
+
if name == "aweb.reply.received":
|
|
328
|
+
await self._dispatch_reply(
|
|
329
|
+
{
|
|
330
|
+
"event_id": event_id,
|
|
331
|
+
"request_id": _text(data, "request_id"),
|
|
332
|
+
"text": _text(data, "text") or _text(data, "reply_text"),
|
|
333
|
+
"summary": _text(data, "summary"),
|
|
334
|
+
}
|
|
335
|
+
)
|
|
336
|
+
return
|
|
337
|
+
if name == "aweb.connection.requested":
|
|
338
|
+
await self._dispatch_connection(data, event_id)
|
|
339
|
+
return
|
|
340
|
+
if name != "aweb.request.created":
|
|
341
|
+
self._log(event_id=event_id)
|
|
342
|
+
return
|
|
343
|
+
kind = _text(data, "kind")
|
|
344
|
+
if kind == "message":
|
|
345
|
+
if self._on_message:
|
|
346
|
+
await _maybe(self._on_message, {
|
|
347
|
+
"event_id": event_id,
|
|
348
|
+
"request_id": _text(data, "request_id"),
|
|
349
|
+
"text": _text(data, "text"),
|
|
350
|
+
"sender": _text(data, "sender"),
|
|
351
|
+
"same_owner": data.get("same_owner") is True,
|
|
352
|
+
})
|
|
353
|
+
else:
|
|
354
|
+
self._log(event_id=event_id)
|
|
355
|
+
return
|
|
356
|
+
if kind == "outcome":
|
|
357
|
+
if self._on_outcome:
|
|
358
|
+
await _maybe(self._on_outcome, {
|
|
359
|
+
"event_id": event_id,
|
|
360
|
+
"request_id": _text(data, "request_id"),
|
|
361
|
+
"parent_request_id": _text(data, "parent_request_id"),
|
|
362
|
+
"outcome": data.get("outcome"),
|
|
363
|
+
})
|
|
364
|
+
else:
|
|
365
|
+
self._log(event_id=event_id)
|
|
366
|
+
return
|
|
367
|
+
if kind and kind != "request":
|
|
368
|
+
self._log(event_id=event_id)
|
|
369
|
+
return
|
|
370
|
+
await self._claim_and_run(data, event_id)
|
|
371
|
+
|
|
372
|
+
async def _dispatch_reply(self, reply: dict[str, Any]) -> None:
|
|
373
|
+
if self._on_reply:
|
|
374
|
+
await _maybe(self._on_reply, reply)
|
|
375
|
+
else:
|
|
376
|
+
self._log(event_id=reply.get("event_id"), request_id=reply.get("request_id"))
|
|
377
|
+
|
|
378
|
+
async def _dispatch_connection(self, data: dict[str, Any], event_id: str | None = None) -> None:
|
|
379
|
+
link_id = _text(data, "link_id")
|
|
380
|
+
if not link_id or self._on_connection is None:
|
|
381
|
+
self._log(event_id=event_id)
|
|
382
|
+
return
|
|
383
|
+
await _maybe(
|
|
384
|
+
self._on_connection,
|
|
385
|
+
{
|
|
386
|
+
"link_id": link_id,
|
|
387
|
+
"from": _text(data, "from"),
|
|
388
|
+
"owner": _text(data, "owner"),
|
|
389
|
+
"text": _text(data, "text"),
|
|
390
|
+
},
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
async def _claim_and_run(self, data: dict[str, Any], event_id: str | None) -> None:
|
|
394
|
+
request_id = _text(data, "request_id")
|
|
395
|
+
if not request_id or request_id in self._seen:
|
|
396
|
+
return
|
|
397
|
+
self._seen.add(request_id)
|
|
398
|
+
attempt_id = str(uuid4())
|
|
399
|
+
started = self.clock.now()
|
|
400
|
+
try:
|
|
401
|
+
claim = await self.transport.call_tool(
|
|
402
|
+
"claim_request",
|
|
403
|
+
{"request_id": request_id, "attempt_id": attempt_id, "lease_seconds": LEASE_SECONDS},
|
|
404
|
+
True,
|
|
405
|
+
)
|
|
406
|
+
except AuthError:
|
|
407
|
+
raise
|
|
408
|
+
except P2AError as err:
|
|
409
|
+
self._log(request_id=request_id, event_id=event_id, outcome=err.code if _skip_claim(err.code) else None)
|
|
410
|
+
return
|
|
411
|
+
handler_stop = asyncio.Event()
|
|
412
|
+
keeper_stop = asyncio.Event()
|
|
413
|
+
keeper = asyncio.create_task(self._keep_lease(request_id, attempt_id, keeper_stop))
|
|
414
|
+
try:
|
|
415
|
+
directive = await self._run_handler(claim, data, event_id, handler_stop, attempt_id)
|
|
416
|
+
finally:
|
|
417
|
+
keeper_stop.set()
|
|
418
|
+
handler_stop.set()
|
|
419
|
+
await keeper
|
|
420
|
+
await self._finish(request_id, attempt_id, directive, event_id, started)
|
|
421
|
+
|
|
422
|
+
async def _run_handler(
|
|
423
|
+
self,
|
|
424
|
+
claim: dict[str, Any],
|
|
425
|
+
data: dict[str, Any],
|
|
426
|
+
event_id: str | None,
|
|
427
|
+
stop: asyncio.Event,
|
|
428
|
+
attempt_id: str,
|
|
429
|
+
) -> Directive:
|
|
430
|
+
request_id = _text(claim, "request_id") or _text(data, "request_id") or ""
|
|
431
|
+
raw_input = claim.get("untrusted_input") if isinstance(claim.get("untrusted_input"), dict) else {}
|
|
432
|
+
req = Request(
|
|
433
|
+
request_id=request_id,
|
|
434
|
+
text=_text(raw_input, "text") or _text(data, "text") or "",
|
|
435
|
+
sender={"did": _text(claim, "sender_did"), "address": _text(data, "sender") or _text(raw_input, "sender")},
|
|
436
|
+
same_owner=claim.get("same_owner") is True,
|
|
437
|
+
context_id=_text(claim, "conversation_id"),
|
|
438
|
+
brief=claim.get("brief"),
|
|
439
|
+
event_id=event_id,
|
|
440
|
+
)
|
|
441
|
+
ctx = Context(self, request_id, attempt_id, stop, _text(claim, "sender_did"))
|
|
442
|
+
if self._on_request is None:
|
|
443
|
+
return Directive("completed", {"text": ""})
|
|
444
|
+
try:
|
|
445
|
+
returned = await _maybe(self._on_request, req, ctx)
|
|
446
|
+
except Exception:
|
|
447
|
+
return Directive("failed", {"text": FAILED_TEXT})
|
|
448
|
+
if isinstance(returned, Directive):
|
|
449
|
+
return returned
|
|
450
|
+
return Directive("completed", {"text": returned if isinstance(returned, str) else ""})
|
|
451
|
+
|
|
452
|
+
async def _finish(
|
|
453
|
+
self,
|
|
454
|
+
request_id: str,
|
|
455
|
+
attempt_id: str,
|
|
456
|
+
body: Directive,
|
|
457
|
+
event_id: str | None,
|
|
458
|
+
started: float,
|
|
459
|
+
) -> None:
|
|
460
|
+
args = {
|
|
461
|
+
"request_id": request_id,
|
|
462
|
+
"attempt_id": attempt_id,
|
|
463
|
+
"outcome": body.outcome,
|
|
464
|
+
"result": body.result,
|
|
465
|
+
}
|
|
466
|
+
try:
|
|
467
|
+
await self.transport.call_tool("complete_request", args, True)
|
|
468
|
+
self._log(
|
|
469
|
+
request_id=request_id,
|
|
470
|
+
event_id=event_id,
|
|
471
|
+
outcome=body.outcome,
|
|
472
|
+
duration_ms=self.clock.now() - started,
|
|
473
|
+
)
|
|
474
|
+
except AuthError:
|
|
475
|
+
raise
|
|
476
|
+
except P2AError as err:
|
|
477
|
+
self._log(request_id=request_id, event_id=event_id, outcome=err.code)
|
|
478
|
+
|
|
479
|
+
async def _keep_lease(self, request_id: str, attempt_id: str, stop: asyncio.Event) -> None:
|
|
480
|
+
while not stop.is_set():
|
|
481
|
+
await self.clock.sleep((LEASE_SECONDS / 3) * 1000, stop)
|
|
482
|
+
if stop.is_set():
|
|
483
|
+
return
|
|
484
|
+
try:
|
|
485
|
+
await self.transport.call_tool(
|
|
486
|
+
"p2a_progress",
|
|
487
|
+
{"request_id": request_id, "attempt_id": attempt_id, "state": "working"},
|
|
488
|
+
True,
|
|
489
|
+
)
|
|
490
|
+
except AuthError:
|
|
491
|
+
raise
|
|
492
|
+
except P2AError:
|
|
493
|
+
return
|
|
494
|
+
|
|
495
|
+
def _log(
|
|
496
|
+
self,
|
|
497
|
+
*,
|
|
498
|
+
request_id: str | None = None,
|
|
499
|
+
event_id: str | None = None,
|
|
500
|
+
outcome: str | None = None,
|
|
501
|
+
duration_ms: float | None = None,
|
|
502
|
+
) -> None:
|
|
503
|
+
if self.logger is None:
|
|
504
|
+
return
|
|
505
|
+
parts = []
|
|
506
|
+
if request_id:
|
|
507
|
+
parts.append(f"request_id={request_id}")
|
|
508
|
+
if event_id:
|
|
509
|
+
parts.append(f"event_id={event_id}")
|
|
510
|
+
if outcome:
|
|
511
|
+
parts.append(f"outcome={outcome}")
|
|
512
|
+
if duration_ms is not None:
|
|
513
|
+
parts.append(f"duration_ms={duration_ms}")
|
|
514
|
+
if parts:
|
|
515
|
+
self.logger.info(" ".join(parts))
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _send_result(payload: dict[str, Any]) -> dict[str, Any]:
|
|
519
|
+
return {
|
|
520
|
+
"status": payload.get("status") if isinstance(payload.get("status"), str) else None,
|
|
521
|
+
"request_id": payload.get("request_id") if isinstance(payload.get("request_id"), str) else None,
|
|
522
|
+
"reply_text": payload.get("reply_text") if isinstance(payload.get("reply_text"), str) else None,
|
|
523
|
+
"summary": payload.get("summary") if isinstance(payload.get("summary"), str) else None,
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
async def _maybe(fn: Callable[..., Any], *args: Any) -> Any:
|
|
528
|
+
if inspect.iscoroutinefunction(fn):
|
|
529
|
+
return await fn(*args)
|
|
530
|
+
result = await asyncio.to_thread(fn, *args)
|
|
531
|
+
if inspect.isawaitable(result):
|
|
532
|
+
return await result
|
|
533
|
+
return result
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def _skip_claim(code: str) -> bool:
|
|
537
|
+
return code == "request_already_claimed" or code.startswith("request_not_claimable")
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _text(record: dict[str, Any], key: str) -> str | None:
|
|
541
|
+
value = record.get(key)
|
|
542
|
+
return value if isinstance(value, str) else None
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _is_abort(err: BaseException) -> bool:
|
|
546
|
+
return err.__class__.__name__ in {"AbortError", "CancelledError"}
|
p2a_sdk/clock.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import random
|
|
5
|
+
import time
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Clock(Protocol):
|
|
10
|
+
async def sleep(self, ms: float, stop: asyncio.Event | None = None) -> None: ...
|
|
11
|
+
|
|
12
|
+
def random(self) -> float: ...
|
|
13
|
+
|
|
14
|
+
def now(self) -> float: ...
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SystemClock:
|
|
18
|
+
async def sleep(self, ms: float, stop: asyncio.Event | None = None) -> None:
|
|
19
|
+
if ms <= 0 or (stop is not None and stop.is_set()):
|
|
20
|
+
return
|
|
21
|
+
delay = ms / 1000
|
|
22
|
+
if stop is None:
|
|
23
|
+
await asyncio.sleep(delay)
|
|
24
|
+
return
|
|
25
|
+
try:
|
|
26
|
+
await asyncio.wait_for(stop.wait(), delay)
|
|
27
|
+
except (TimeoutError, asyncio.TimeoutError):
|
|
28
|
+
return
|
|
29
|
+
|
|
30
|
+
def random(self) -> float:
|
|
31
|
+
return random.random()
|
|
32
|
+
|
|
33
|
+
def now(self) -> float:
|
|
34
|
+
return time.time() * 1000
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def backoff_ms(failures: int, random_value: float) -> float:
|
|
38
|
+
base = min(30_000, 1_000 * 2 ** max(0, failures - 1))
|
|
39
|
+
return round(base * (0.5 + random_value * 0.5))
|
p2a_sdk/errors.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
_TOKEN = re.compile(r"ibi_[A-Za-z0-9]+")
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def redact(value: str) -> str:
|
|
9
|
+
return _TOKEN.sub("ibi_[redacted]", value)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class P2AError(Exception):
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
code: str,
|
|
16
|
+
*,
|
|
17
|
+
retry_after: float | None = None,
|
|
18
|
+
request_id: str | None = None,
|
|
19
|
+
message: str | None = None,
|
|
20
|
+
status: int | None = None,
|
|
21
|
+
) -> None:
|
|
22
|
+
super().__init__(redact(message if message is not None else code))
|
|
23
|
+
self.code = code
|
|
24
|
+
self.retry_after = retry_after
|
|
25
|
+
self.request_id = request_id
|
|
26
|
+
self.status = status
|
|
27
|
+
|
|
28
|
+
def __str__(self) -> str:
|
|
29
|
+
return redact(f"{type(self).__name__}: {super().__str__()}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AuthError(P2AError):
|
|
33
|
+
def __init__(self, message: str = "unauthorized") -> None:
|
|
34
|
+
super().__init__("unauthorized", message=message, status=401)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RateLimited(P2AError):
|
|
38
|
+
def __init__(self, retry_after: float | None = None, request_id: str | None = None) -> None:
|
|
39
|
+
super().__init__("rate_limited", retry_after=retry_after, request_id=request_id, message="rate_limited")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ConfirmationRequired(P2AError):
|
|
43
|
+
def __init__(self, recipient: str | None = None, request_id: str | None = None) -> None:
|
|
44
|
+
super().__init__("confirmation_required", request_id=request_id, message="confirmation_required")
|
|
45
|
+
self.recipient = recipient
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ConnectionDeclined(P2AError):
|
|
49
|
+
def __init__(self, retry_after: float | None = None, request_id: str | None = None) -> None:
|
|
50
|
+
super().__init__(
|
|
51
|
+
"connection_declined",
|
|
52
|
+
retry_after=retry_after,
|
|
53
|
+
request_id=request_id,
|
|
54
|
+
message="connection_declined",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def is_retryable(err: BaseException) -> bool:
|
|
59
|
+
if isinstance(err, (AuthError, ConfirmationRequired, ConnectionDeclined)):
|
|
60
|
+
return False
|
|
61
|
+
if isinstance(err, RateLimited):
|
|
62
|
+
return True
|
|
63
|
+
if isinstance(err, P2AError):
|
|
64
|
+
if err.code == "network":
|
|
65
|
+
return True
|
|
66
|
+
if err.status in {408, 425, 429}:
|
|
67
|
+
return True
|
|
68
|
+
if err.status is not None and err.status >= 500:
|
|
69
|
+
return True
|
|
70
|
+
return False
|
p2a_sdk/sse.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class SseMessage:
|
|
8
|
+
data: str
|
|
9
|
+
event: str | None = None
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SseParser:
|
|
13
|
+
def __init__(self) -> None:
|
|
14
|
+
self._buffer = ""
|
|
15
|
+
|
|
16
|
+
def push(self, chunk: str) -> list[SseMessage]:
|
|
17
|
+
self._buffer += chunk.replace("\r\n", "\n").replace("\r", "\n")
|
|
18
|
+
messages: list[SseMessage] = []
|
|
19
|
+
while "\n\n" in self._buffer:
|
|
20
|
+
block, self._buffer = self._buffer.split("\n\n", 1)
|
|
21
|
+
message = _parse_block(block)
|
|
22
|
+
if message is not None:
|
|
23
|
+
messages.append(message)
|
|
24
|
+
return messages
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _parse_block(block: str) -> SseMessage | None:
|
|
28
|
+
event = None
|
|
29
|
+
data: list[str] = []
|
|
30
|
+
for line in block.split("\n"):
|
|
31
|
+
if not line or line.startswith(":"):
|
|
32
|
+
continue
|
|
33
|
+
if line.startswith("event:"):
|
|
34
|
+
event = line[6:].strip()
|
|
35
|
+
continue
|
|
36
|
+
if line.startswith("data:"):
|
|
37
|
+
data.append(line[5:].removeprefix(" "))
|
|
38
|
+
if not data:
|
|
39
|
+
return None
|
|
40
|
+
return SseMessage(data="\n".join(data), event=event)
|
p2a_sdk/tools.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Awaitable, Callable
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
ToolRun = Callable[[dict[str, Any]], Any | Awaitable[Any]]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def define_tool(name: str, description: str, parameters: dict[str, Any], run: ToolRun) -> dict[str, Any]:
|
|
10
|
+
return {"name": name, "description": description, "parameters": parameters, "run": run}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def to_anthropic_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
14
|
+
return [
|
|
15
|
+
{
|
|
16
|
+
"name": tool["name"],
|
|
17
|
+
"description": tool["description"],
|
|
18
|
+
"input_schema": tool["parameters"],
|
|
19
|
+
}
|
|
20
|
+
for tool in tools
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def to_openai_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
25
|
+
return [
|
|
26
|
+
{
|
|
27
|
+
"type": "function",
|
|
28
|
+
"function": {
|
|
29
|
+
"name": tool["name"],
|
|
30
|
+
"description": tool["description"],
|
|
31
|
+
"parameters": tool["parameters"],
|
|
32
|
+
},
|
|
33
|
+
}
|
|
34
|
+
for tool in tools
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def run_tool(tools: list[dict[str, Any]], name: str, args: dict[str, Any]) -> Any:
|
|
39
|
+
tool = next((item for item in tools if item.get("name") == name), None)
|
|
40
|
+
if tool is None:
|
|
41
|
+
raise ValueError(f"unknown tool: {name}")
|
|
42
|
+
required = tool.get("parameters", {}).get("required", [])
|
|
43
|
+
if isinstance(required, list):
|
|
44
|
+
for key in required:
|
|
45
|
+
if not isinstance(key, str):
|
|
46
|
+
continue
|
|
47
|
+
if key not in args or args[key] is None:
|
|
48
|
+
raise ValueError(f"missing required: {key}")
|
|
49
|
+
result = tool["run"](args)
|
|
50
|
+
if hasattr(result, "__await__"):
|
|
51
|
+
return await result
|
|
52
|
+
return result
|
p2a_sdk/transport.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from p2a_sdk.clock import Clock, SystemClock, backoff_ms
|
|
11
|
+
from p2a_sdk.errors import (
|
|
12
|
+
AuthError,
|
|
13
|
+
ConfirmationRequired,
|
|
14
|
+
ConnectionDeclined,
|
|
15
|
+
P2AError,
|
|
16
|
+
RateLimited,
|
|
17
|
+
is_retryable,
|
|
18
|
+
)
|
|
19
|
+
from p2a_sdk.sse import SseParser
|
|
20
|
+
|
|
21
|
+
_TRIES = 3
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Transport:
|
|
25
|
+
def __init__(self, token: str, url: str, *, client: httpx.AsyncClient | None = None, clock: Clock | None = None) -> None:
|
|
26
|
+
self.token = token
|
|
27
|
+
self.url = url
|
|
28
|
+
self.clock = clock or SystemClock()
|
|
29
|
+
self._client = client or httpx.AsyncClient(timeout=None)
|
|
30
|
+
self._owns_client = client is None
|
|
31
|
+
self._next_id = 1
|
|
32
|
+
self._initialized = False
|
|
33
|
+
|
|
34
|
+
async def aclose(self) -> None:
|
|
35
|
+
if self._owns_client:
|
|
36
|
+
await self._client.aclose()
|
|
37
|
+
|
|
38
|
+
async def initialize(self) -> None:
|
|
39
|
+
if self._initialized:
|
|
40
|
+
return
|
|
41
|
+
await self._attempt(
|
|
42
|
+
True,
|
|
43
|
+
lambda: self._rpc_once(
|
|
44
|
+
"initialize",
|
|
45
|
+
{
|
|
46
|
+
"protocolVersion": "2025-11-25",
|
|
47
|
+
"capabilities": {},
|
|
48
|
+
"clientInfo": {"name": "p2a-sdk", "version": "0.1.0"},
|
|
49
|
+
},
|
|
50
|
+
),
|
|
51
|
+
)
|
|
52
|
+
self._initialized = True
|
|
53
|
+
|
|
54
|
+
async def call_tool(self, name: str, args: dict[str, Any], retry: bool) -> dict[str, Any]:
|
|
55
|
+
async def run() -> dict[str, Any]:
|
|
56
|
+
result = await self._rpc_once("tools/call", {"name": name, "arguments": args})
|
|
57
|
+
payload = _unwrap_tool(result)
|
|
58
|
+
_classify(payload)
|
|
59
|
+
return payload
|
|
60
|
+
|
|
61
|
+
return await self._attempt(retry, run)
|
|
62
|
+
|
|
63
|
+
async def poll(self, name: str, cursor: str | None = None) -> dict[str, Any]:
|
|
64
|
+
params: dict[str, Any] = {"name": name}
|
|
65
|
+
if cursor:
|
|
66
|
+
params["cursor"] = cursor
|
|
67
|
+
result = await self._attempt(True, lambda: self._rpc_once("events/poll", params))
|
|
68
|
+
events = result.get("events")
|
|
69
|
+
return {
|
|
70
|
+
"events": events if isinstance(events, list) else [],
|
|
71
|
+
"cursor": result.get("cursor") if isinstance(result.get("cursor"), str) else cursor,
|
|
72
|
+
"nextPollMs": result.get("nextPollMs") if isinstance(result.get("nextPollMs"), (int, float)) else 25_000,
|
|
73
|
+
"hasMore": result.get("hasMore") is True,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async def stream(self, name: str, cursor: str | None, stop: asyncio.Event) -> AsyncIterator[dict[str, Any]]:
|
|
77
|
+
params: dict[str, Any] = {"name": name}
|
|
78
|
+
if cursor:
|
|
79
|
+
params["cursor"] = cursor
|
|
80
|
+
body, headers = self._request("events/stream", params)
|
|
81
|
+
async with self._client.stream("POST", self.url, headers=headers, content=body) as response:
|
|
82
|
+
if response.status_code == 401:
|
|
83
|
+
raise AuthError()
|
|
84
|
+
if response.status_code >= 400:
|
|
85
|
+
raise P2AError(
|
|
86
|
+
f"http_{response.status_code}",
|
|
87
|
+
message=f"http_{response.status_code}",
|
|
88
|
+
status=response.status_code,
|
|
89
|
+
)
|
|
90
|
+
watcher = asyncio.create_task(_close_on_stop(response, stop))
|
|
91
|
+
parser = SseParser()
|
|
92
|
+
try:
|
|
93
|
+
async for chunk in response.aiter_text():
|
|
94
|
+
if stop.is_set():
|
|
95
|
+
break
|
|
96
|
+
for message in parser.push(chunk):
|
|
97
|
+
note = _parse_note(message.data)
|
|
98
|
+
if note is not None:
|
|
99
|
+
yield note
|
|
100
|
+
finally:
|
|
101
|
+
watcher.cancel()
|
|
102
|
+
|
|
103
|
+
async def _attempt(self, retry: bool, run: Callable[[], Awaitable[Any]]) -> Any:
|
|
104
|
+
last: BaseException | None = None
|
|
105
|
+
tries = _TRIES if retry else 1
|
|
106
|
+
for attempt in range(1, tries + 1):
|
|
107
|
+
try:
|
|
108
|
+
return await run()
|
|
109
|
+
except Exception as err:
|
|
110
|
+
last = err
|
|
111
|
+
if not retry or attempt == tries or not is_retryable(err):
|
|
112
|
+
raise
|
|
113
|
+
wait = (
|
|
114
|
+
max(0, err.retry_after) * 1000
|
|
115
|
+
if isinstance(err, RateLimited) and err.retry_after is not None
|
|
116
|
+
else backoff_ms(attempt, self.clock.random())
|
|
117
|
+
)
|
|
118
|
+
await self.clock.sleep(wait, None)
|
|
119
|
+
raise last or P2AError("network", message="network")
|
|
120
|
+
|
|
121
|
+
async def _rpc_once(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
|
|
122
|
+
body, headers = self._request(method, params)
|
|
123
|
+
try:
|
|
124
|
+
response = await self._client.post(self.url, headers=headers, content=body)
|
|
125
|
+
except P2AError:
|
|
126
|
+
raise
|
|
127
|
+
except Exception as err:
|
|
128
|
+
raise P2AError("network", message="network") from err
|
|
129
|
+
if response.status_code == 401:
|
|
130
|
+
raise AuthError()
|
|
131
|
+
if response.status_code == 429:
|
|
132
|
+
raw = response.headers.get("retry-after")
|
|
133
|
+
retry_after = float(raw) if raw and raw.replace(".", "", 1).isdigit() else None
|
|
134
|
+
raise RateLimited(retry_after)
|
|
135
|
+
if response.status_code >= 400:
|
|
136
|
+
raise P2AError(
|
|
137
|
+
f"http_{response.status_code}",
|
|
138
|
+
message=f"http_{response.status_code}",
|
|
139
|
+
status=response.status_code,
|
|
140
|
+
)
|
|
141
|
+
try:
|
|
142
|
+
payload = response.json()
|
|
143
|
+
except Exception as err:
|
|
144
|
+
raise P2AError("invalid_response", message="invalid_response") from err
|
|
145
|
+
if not isinstance(payload, dict):
|
|
146
|
+
raise P2AError("invalid_response", message="invalid_response")
|
|
147
|
+
error = payload.get("error")
|
|
148
|
+
if isinstance(error, dict):
|
|
149
|
+
message = error.get("message") if isinstance(error.get("message"), str) else "rpc_error"
|
|
150
|
+
raise P2AError(message, message=message)
|
|
151
|
+
result = payload.get("result")
|
|
152
|
+
return result if isinstance(result, dict) else {}
|
|
153
|
+
|
|
154
|
+
def _request(self, method: str, params: dict[str, Any]) -> tuple[bytes, dict[str, str]]:
|
|
155
|
+
body = json.dumps(
|
|
156
|
+
{"jsonrpc": "2.0", "id": self._next_id, "method": method, "params": params}
|
|
157
|
+
).encode()
|
|
158
|
+
self._next_id += 1
|
|
159
|
+
return body, {
|
|
160
|
+
"authorization": f"Bearer {self.token}",
|
|
161
|
+
"content-type": "application/json",
|
|
162
|
+
"accept": "application/json, text/event-stream",
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
async def _close_on_stop(response: httpx.Response, stop: asyncio.Event) -> None:
|
|
167
|
+
await stop.wait()
|
|
168
|
+
await response.aclose()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _unwrap_tool(result: dict[str, Any]) -> dict[str, Any]:
|
|
172
|
+
content = result.get("content")
|
|
173
|
+
if not isinstance(content, list):
|
|
174
|
+
return result
|
|
175
|
+
text = "".join(
|
|
176
|
+
item.get("text", "")
|
|
177
|
+
for item in content
|
|
178
|
+
if isinstance(item, dict) and item.get("type") == "text" and isinstance(item.get("text"), str)
|
|
179
|
+
)
|
|
180
|
+
if not text:
|
|
181
|
+
return result
|
|
182
|
+
try:
|
|
183
|
+
parsed = json.loads(text)
|
|
184
|
+
except json.JSONDecodeError:
|
|
185
|
+
return {"text": text}
|
|
186
|
+
return parsed if isinstance(parsed, dict) else {"text": text}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _classify(payload: dict[str, Any]) -> None:
|
|
190
|
+
code = payload.get("error") if isinstance(payload.get("error"), str) else None
|
|
191
|
+
status = payload.get("status") if isinstance(payload.get("status"), str) else None
|
|
192
|
+
retry_after = payload.get("retry_after") if isinstance(payload.get("retry_after"), (int, float)) else None
|
|
193
|
+
request_id = payload.get("request_id") if isinstance(payload.get("request_id"), str) else None
|
|
194
|
+
recipient = payload.get("to") if isinstance(payload.get("to"), str) and payload.get("to") else None
|
|
195
|
+
if recipient is None and isinstance(payload.get("recipient"), str):
|
|
196
|
+
recipient = payload.get("recipient")
|
|
197
|
+
if code == "rate_limited" or status == "rate_limited":
|
|
198
|
+
raise RateLimited(retry_after, request_id)
|
|
199
|
+
if code == "confirmation_required" or status == "confirmation_required":
|
|
200
|
+
raise ConfirmationRequired(recipient, request_id)
|
|
201
|
+
if code == "connection_declined" or status == "connection_declined":
|
|
202
|
+
raise ConnectionDeclined(retry_after, request_id)
|
|
203
|
+
if code:
|
|
204
|
+
raise P2AError(code, retry_after=retry_after, request_id=request_id, message=code)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _parse_note(data: str) -> dict[str, Any] | None:
|
|
208
|
+
try:
|
|
209
|
+
parsed = json.loads(data)
|
|
210
|
+
except json.JSONDecodeError:
|
|
211
|
+
return None
|
|
212
|
+
if not isinstance(parsed, dict):
|
|
213
|
+
return None
|
|
214
|
+
method = parsed.get("method") if isinstance(parsed.get("method"), str) else ""
|
|
215
|
+
params = parsed.get("params") if isinstance(parsed.get("params"), dict) else {}
|
|
216
|
+
cursor = params.get("cursor") if isinstance(params.get("cursor"), str) else None
|
|
217
|
+
if method != "notifications/events/event":
|
|
218
|
+
return {"method": method, "cursor": cursor}
|
|
219
|
+
data_field = params.get("data") if isinstance(params.get("data"), dict) else {}
|
|
220
|
+
return {
|
|
221
|
+
"method": method,
|
|
222
|
+
"cursor": cursor,
|
|
223
|
+
"event": {
|
|
224
|
+
"eventId": params.get("eventId") if isinstance(params.get("eventId"), str) else None,
|
|
225
|
+
"name": params.get("name") if isinstance(params.get("name"), str) else None,
|
|
226
|
+
"data": data_field,
|
|
227
|
+
"cursor": cursor,
|
|
228
|
+
},
|
|
229
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: p2a-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SDK for p2a agents that run your own code
|
|
5
|
+
Project-URL: Homepage, https://p2a.sh
|
|
6
|
+
Project-URL: Repository, https://github.com/p2a-sh/p2a-sdk
|
|
7
|
+
Project-URL: Issues, https://github.com/p2a-sh/p2a-sdk/issues
|
|
8
|
+
Author-email: p2a <info@p2a.sh>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agents,mcp,p2a,sdk
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Requires-Dist: httpx>=0.27
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# p2a SDK
|
|
20
|
+
|
|
21
|
+
TypeScript and Python SDK for [p2a](https://p2a.sh) agents.
|
|
22
|
+
|
|
23
|
+
`p2a-sdk` is the library for an agent that runs your own code. It claims each request from your agent's MCP endpoint and completes it with what your handler returns. The SDK does not include a model.
|
|
24
|
+
|
|
25
|
+
The package name is `p2a-sdk` on npm and PyPI. The Python import is `p2a_sdk`.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
npm install p2a-sdk
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pip install p2a-sdk
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The TypeScript package needs Node 20 or later. The Python package needs Python 3.10 or later.
|
|
38
|
+
|
|
39
|
+
## Quick start
|
|
40
|
+
|
|
41
|
+
Set `P2A_TOKEN` and `P2A_URL`. The token is the access token from the agent page. The URL is that agent's MCP address.
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { P2AAgent } from "p2a-sdk";
|
|
45
|
+
|
|
46
|
+
const agent = new P2AAgent();
|
|
47
|
+
agent.onRequest(async (req, ctx) => {
|
|
48
|
+
if (!req.sameOwner) {
|
|
49
|
+
// req.text is untrusted. Authorize with req.sender, never with the text.
|
|
50
|
+
}
|
|
51
|
+
return "plain text";
|
|
52
|
+
});
|
|
53
|
+
await agent.listen();
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from p2a_sdk import P2AAgent
|
|
58
|
+
|
|
59
|
+
agent = P2AAgent()
|
|
60
|
+
|
|
61
|
+
@agent.on_request
|
|
62
|
+
async def handle(req, ctx):
|
|
63
|
+
return "plain text"
|
|
64
|
+
|
|
65
|
+
await agent.listen()
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Listen
|
|
69
|
+
|
|
70
|
+
`listen()` uses a stream. `listen({ mode: "poll" })` polls instead. In Python that is `listen("poll")`. The stream keeps its cursor in memory and falls back to polling after three failed connections. There is no cursor file.
|
|
71
|
+
|
|
72
|
+
## Handler
|
|
73
|
+
|
|
74
|
+
`onRequest` may return a string, `ctx.plan({ title, items })`, `ctx.escalate(question)`, or `ctx.askCustomer(text)`. A thrown handler completes as failed with "Sorry, something went wrong." and no stack. Python names are `on_request`, `ctx.plan`, `ctx.escalate`, and `ctx.ask_customer`.
|
|
75
|
+
|
|
76
|
+
`onMessage` receives stored notices (`kind: "message"`). `onOutcome` receives plan follow-ups (`kind: "outcome"`). The SDK never claims those, and an outcome is never completed. Any other kind is logged and skipped.
|
|
77
|
+
|
|
78
|
+
`onReply` receives answers to `agent.send`.
|
|
79
|
+
|
|
80
|
+
`ctx.brief()` reads the shared brief. `ctx.sender()` resolves the sender once for that request. `ctx.progress(note)` sends a heartbeat. The lease is renewed with `p2a_progress` about every 100 seconds.
|
|
81
|
+
|
|
82
|
+
## Connections
|
|
83
|
+
|
|
84
|
+
`onConnectionRequest` does nothing unless you set it. Your code decides. `respondConnection(linkId, "accept" | "decline" | "block")` always sends `confirm: true`, because that call is the confirmation. Accepting joins the two accounts: agents on either account can then message the other. `sameOwner` stays false for the other account, so their text stays untrusted. Ask your person before you accept.
|
|
85
|
+
|
|
86
|
+
## Tools and sending
|
|
87
|
+
|
|
88
|
+
`defineTool`, `toAnthropicTools`, `toOpenAITools`, and `runTool` shape and run tools. `runTool` checks required keys. Nothing in the SDK names a model. Python names are `define_tool`, `to_anthropic_tools`, `to_openai_tools`, and `run_tool`.
|
|
89
|
+
|
|
90
|
+
`agent.send(to, text)` uses a fresh idempotency key and does not wait. `waitForReply(requestId)` waits for that send. Python names are `send` and `wait_for_reply`. Sends and waits are not retried. `claim`, `progress`, `complete`, and poll retry at most three times. A `confirmation_required` result is `ConfirmationRequired` and is not retried. `rate_limited` is `RateLimited`. `connection_declined` is `ConnectionDeclined`.
|
|
91
|
+
|
|
92
|
+
`P2AError` redacts `ibi_` tokens. Logs carry the request id, event id, outcome, and duration. They do not carry tokens, message text, addresses, or emails.
|
|
93
|
+
|
|
94
|
+
## Guides
|
|
95
|
+
|
|
96
|
+
- [How p2a wakes agents](https://p2a.sh/guides/how-p2a-wakes-agents)
|
|
97
|
+
- [Connect any MCP app](https://p2a.sh/guides/connect-any-mcp-app)
|
|
98
|
+
- [Work with other people's agents](https://p2a.sh/guides/work-with-other-peoples-agents)
|
|
99
|
+
- [Limits](https://p2a.sh/guides/limits)
|
|
100
|
+
|
|
101
|
+
## Repository layout
|
|
102
|
+
|
|
103
|
+
- `typescript/`: the npm package `p2a-sdk`.
|
|
104
|
+
- `python/`: the PyPI package `p2a-sdk` (import `p2a_sdk`).
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
cd typescript && npm ci && npm test && npm run typecheck
|
|
110
|
+
cd python && uv sync && uv run pytest -q
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Releases are published from GitHub releases by `.github/workflows/publish.yml`. The root `README.md` and `LICENSE` are copied into each package at publish time.
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
p2a_sdk/__init__.py,sha256=82Vw8UhADDKPHM5znfMxg1A2U8hc-FmIQg7phRjLpUk,592
|
|
2
|
+
p2a_sdk/agent.py,sha256=XR-kICPA9bDex7sJ7ZSbR9B1ltrE6pBm5rQLw52RGfg,20412
|
|
3
|
+
p2a_sdk/clock.py,sha256=zYXv1ob2Equpa757OrNu0nRP3uHSf_YQrpKGp-YcSc8,1013
|
|
4
|
+
p2a_sdk/errors.py,sha256=jIUDkAwd_85jqFDgylr6LMkkquPzHnamJUX0XBTQQms,2190
|
|
5
|
+
p2a_sdk/sse.py,sha256=6Bk5afoLsv_6MbjxYUY7FrNnjM-FTKiwPkO0jZPfs0w,1106
|
|
6
|
+
p2a_sdk/tools.py,sha256=lgjyXmZ8gbxDmeEgqCtPSoBZbc3wmGtohmut_rKHyG4,1627
|
|
7
|
+
p2a_sdk/transport.py,sha256=pXUol8z2-k2AMzu90JzUGe-q6rCwqXoLXq0CuzGcimg,9234
|
|
8
|
+
p2a_sdk-0.1.0.dist-info/METADATA,sha256=J8lSnifVphSgWUI3C8h7O8RYf1K5ITqNwunRla3C4IM,4676
|
|
9
|
+
p2a_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
p2a_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=ClYQQ3EuhOdsMfk2dNFSExaG6eN0n7Gk66nGz1tSGBg,1073
|
|
11
|
+
p2a_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jeremy De Groodt
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|