memro 0.2.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.
memro/client.py ADDED
@@ -0,0 +1,547 @@
1
+ """
2
+ Low-level HTTP client for the Memro API.
3
+
4
+ Every method maps to one endpoint (see docs/api-reference.md). Most code
5
+ should use :class:`memro.Agent`, which keeps the credentials for you.
6
+ """
7
+ import json
8
+ import mimetypes
9
+ import os
10
+ import time
11
+ from typing import Any, Dict, List, Optional, Tuple, Union
12
+ from urllib.parse import urlencode
13
+
14
+ import requests
15
+ from requests import Response
16
+
17
+ from .crypto import generate_keypair, sign_body, sign_request, solve_pow
18
+
19
+ DEFAULT_BASE_URL = "https://api.memro.co"
20
+ API_KEY_PREFIX = "memro_sk_"
21
+
22
+ FileInput = Union[str, os.PathLike, Tuple[str, bytes], Tuple[str, bytes, str]]
23
+
24
+
25
+ class MemroError(Exception):
26
+ """Raised when the Memro API returns an error."""
27
+
28
+ def __init__(self, status_code: int, message: str):
29
+ self.status_code = status_code
30
+ self.message = message
31
+ super().__init__(f"[{status_code}] {message}")
32
+
33
+
34
+ class RateLimitError(MemroError):
35
+ """HTTP 429: slow down and retry later."""
36
+
37
+
38
+ class MemroClient:
39
+ """
40
+ HTTP client for the Memro API.
41
+
42
+ MemroClient(api_key="memro_sk_...") # Memro Cloud
43
+ MemroClient("http://localhost:8081") # self-hosted, signed requests
44
+ MemroClient() # MEMRO_BASE_URL / MEMRO_API_KEY from env
45
+
46
+ Authentication is either an API key (``Authorization: Bearer``) or an
47
+ ed25519 signature made with the agent's private key, passed per call.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ base_url: Optional[str] = None,
53
+ api_key: Optional[str] = None,
54
+ timeout: float = 30.0,
55
+ max_retries: int = 2,
56
+ ):
57
+ self.base_url = (base_url or os.getenv("MEMRO_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
58
+ self.api_key = api_key or os.getenv("MEMRO_API_KEY") or None
59
+ if self.api_key and not self.api_key.startswith(API_KEY_PREFIX):
60
+ raise ValueError("API keys start with memro_sk_. Create one with `npx memro-cli connect` or in the dashboard.")
61
+ self.timeout = timeout
62
+ self.max_retries = max_retries
63
+ self._session = requests.Session()
64
+
65
+ # ── Plumbing ────────────────────────────────────────────────────────────
66
+
67
+ def _headers(self, method: str, path_and_query: str, body: bytes,
68
+ agent_id: Optional[str], private_key: Optional[str]) -> Dict[str, str]:
69
+ """Authentication headers for one request. Override to add headers."""
70
+ if self.api_key:
71
+ return {"Authorization": f"Bearer {self.api_key}"}
72
+ if agent_id and private_key:
73
+ headers = sign_request(private_key, method, path_and_query, body)
74
+ headers["X-Agent-Id"] = agent_id
75
+ return headers
76
+ return {}
77
+
78
+ def _auth_headers(self, agent_id: str, private_key: str, body: bytes) -> dict:
79
+ """Deprecated: legacy v1 signing headers. Use the client methods instead."""
80
+ if self.api_key:
81
+ return {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
82
+ headers = sign_body(private_key, body)
83
+ headers["X-Agent-Id"] = agent_id
84
+ headers["Content-Type"] = "application/json"
85
+ return headers
86
+
87
+ def _authenticated(self, private_key: Optional[str]) -> bool:
88
+ return bool(self.api_key or private_key)
89
+
90
+ @staticmethod
91
+ def _raise(resp: Response) -> None:
92
+ if resp.ok:
93
+ return
94
+ try:
95
+ body = resp.json()
96
+ msg = body.get("message") or body.get("error") or resp.text
97
+ except ValueError:
98
+ msg = resp.text or resp.reason
99
+ cls = RateLimitError if resp.status_code == 429 else MemroError
100
+ raise cls(resp.status_code, msg)
101
+
102
+ def request(
103
+ self,
104
+ method: str,
105
+ path: str,
106
+ *,
107
+ params: Optional[Dict[str, Any]] = None,
108
+ json_body: Any = None,
109
+ files: Optional[Dict[str, Tuple[str, bytes, str]]] = None,
110
+ data: Optional[Dict[str, str]] = None,
111
+ agent_id: Optional[str] = None,
112
+ private_key: Optional[str] = None,
113
+ auth: bool = True,
114
+ ) -> Response:
115
+ """Send a request and return the response, raising MemroError on failure.
116
+
117
+ The signature covers the exact path, query string and body that are
118
+ sent, so the URL is built here rather than by ``requests``.
119
+ """
120
+ query = {k: _param(v) for k, v in (params or {}).items() if v is not None}
121
+ path_and_query = path + ("?" + urlencode(query) if query else "")
122
+ url = self.base_url + path_and_query
123
+
124
+ for attempt in range(self.max_retries + 1):
125
+ headers: Dict[str, str] = {"Accept": "application/json"}
126
+ if files is not None:
127
+ prepared = requests.Request(method, url, files=files, data=data).prepare()
128
+ body = prepared.body or b""
129
+ headers["Content-Type"] = prepared.headers["Content-Type"]
130
+ elif json_body is not None:
131
+ body = json.dumps(json_body).encode()
132
+ headers["Content-Type"] = "application/json"
133
+ else:
134
+ body = b""
135
+ if auth:
136
+ headers.update(self._headers(method, path_and_query, body, agent_id, private_key))
137
+ resp = self._session.request(method, url, data=body or None, headers=headers, timeout=self.timeout)
138
+ # Signed requests carry a fresh timestamp and signature on each attempt.
139
+ # 429 means the request was not processed; gateway errors are only
140
+ # retried for requests that are safe to repeat.
141
+ retry = resp.status_code == 429 or (resp.status_code in (502, 503, 504) and method in ("GET", "DELETE"))
142
+ # Signatures are deterministic, so an identical signed request in the
143
+ # same second is refused as a replay; re-sign in the next second.
144
+ if resp.status_code == 401 and "already used" in resp.text and "X-Signature" in headers and attempt < self.max_retries:
145
+ time.sleep(1.05 - (time.time() % 1))
146
+ continue
147
+ if retry and attempt < self.max_retries:
148
+ time.sleep(_retry_delay(resp, attempt))
149
+ continue
150
+ self._raise(resp)
151
+ return resp
152
+ raise AssertionError("unreachable")
153
+
154
+ def _json(self, method: str, path: str, **kw) -> Any:
155
+ resp = self.request(method, path, **kw)
156
+ return resp.json() if resp.content else None
157
+
158
+ # ── Account ─────────────────────────────────────────────────────────────
159
+
160
+ def whoami(self, agent_id: Optional[str] = None, private_key: Optional[str] = None) -> dict:
161
+ """The agent this client's credential acts as: {agent_id, tenant_id, user_id, auth}."""
162
+ return self._json("GET", "/auth/whoami", agent_id=agent_id, private_key=private_key)
163
+
164
+ def health(self) -> dict:
165
+ return self._json("GET", "/health", auth=False)
166
+
167
+ # ── Identity ────────────────────────────────────────────────────────────
168
+
169
+ def create_identity(self) -> dict:
170
+ """
171
+ Generate an ed25519 key pair locally and register the public key.
172
+ Returns {"agent_id": str, "private_key": str}; the private key never
173
+ leaves this machine.
174
+ """
175
+ public_key, private_key = generate_keypair()
176
+ body: Dict[str, Any] = {"public_key": public_key}
177
+ pow_params = self._pow_params()
178
+ if pow_params is not None:
179
+ timestamp, nonce = solve_pow(public_key, int(pow_params.get("difficulty", 0)))
180
+ body["pow"] = {"timestamp": timestamp, "nonce": nonce}
181
+ data = self._json("POST", "/identity", json_body=body, auth=False)
182
+ data["private_key"] = private_key
183
+ return data
184
+
185
+ def _pow_params(self) -> Optional[dict]:
186
+ """The server's registration proof-of-work settings, or None if it has none."""
187
+ try:
188
+ return self._json("GET", "/identity/pow", auth=False)
189
+ except MemroError as e:
190
+ if e.status_code == 404:
191
+ return None
192
+ raise
193
+
194
+ def get_identity(self, agent_id: str) -> dict:
195
+ """Whether an agent is registered: {id, created_at}. The owner is not public."""
196
+ return self._json("GET", f"/identity/{agent_id}", auth=False)
197
+
198
+ def delete_identity(self, agent_id: str, private_key: Optional[str] = None) -> None:
199
+ """Delete the agent and all of its memories, files, keys and webhooks."""
200
+ self.request("DELETE", f"/identity/{agent_id}", agent_id=agent_id, private_key=private_key)
201
+
202
+ # ── Memories ────────────────────────────────────────────────────────────
203
+
204
+ def create_memory(
205
+ self,
206
+ agent_id: str,
207
+ private_key: Optional[str],
208
+ content: str,
209
+ memory_type: Optional[str] = None,
210
+ visibility: str = "private",
211
+ event_date: Optional[str] = None,
212
+ session_id: Optional[str] = None,
213
+ is_atomic: bool = False,
214
+ metadata: Optional[dict] = None,
215
+ ) -> dict:
216
+ """Store a memory. memory_type None (or "auto") lets the server classify it."""
217
+ body: Dict[str, Any] = {"agent_id": agent_id, "content": content, "visibility": visibility, "is_atomic": is_atomic}
218
+ if memory_type:
219
+ body["memory_type"] = memory_type
220
+ if event_date:
221
+ body["event_date"] = event_date
222
+ if session_id:
223
+ body["session_id"] = session_id
224
+ if metadata:
225
+ body["metadata"] = metadata
226
+ return self._json("POST", "/memory", json_body=body, agent_id=agent_id, private_key=private_key)
227
+
228
+ def create_memories_batch(
229
+ self,
230
+ agent_id: str,
231
+ private_key: Optional[str],
232
+ memories: List[Dict[str, Any]],
233
+ ) -> dict:
234
+ """Store up to 500 memories in a single transaction. Returns {'ids': [...], 'count': N, 'memories': [...]}."""
235
+ formatted = []
236
+ for item in memories:
237
+ entry = dict(item)
238
+ if "agent_id" not in entry:
239
+ entry["agent_id"] = agent_id
240
+ formatted.append(entry)
241
+ return self._json("POST", "/memories/batch", json_body=formatted, agent_id=agent_id, private_key=private_key)
242
+
243
+
244
+ def get_memories(
245
+ self,
246
+ agent_id: str,
247
+ private_key: Optional[str] = None,
248
+ memory_type: Optional[str] = None,
249
+ visibility: Optional[str] = None,
250
+ limit: Optional[int] = None,
251
+ ) -> List[dict]:
252
+ """The agent's most recent memories, newest first (at most 100)."""
253
+ params = {"memory_type": memory_type, "visibility": visibility, "limit": limit}
254
+ return self._json("GET", f"/memory/agent/{agent_id}", params=params, agent_id=agent_id, private_key=private_key)
255
+
256
+ def delete_memory(self, agent_id: str, private_key: Optional[str], memory_id: str) -> bool:
257
+ """Delete a memory. Returns False if it does not exist."""
258
+ try:
259
+ self.request("DELETE", f"/memory/{memory_id}", agent_id=agent_id, private_key=private_key)
260
+ return True
261
+ except MemroError as e:
262
+ if e.status_code == 404:
263
+ return False
264
+ raise
265
+
266
+ def export(self, agent_id: str, private_key: Optional[str] = None) -> dict:
267
+ """Every memory the agent has: {agent_id, exported_at, total, memories}."""
268
+ return self._json("GET", f"/export/{agent_id}", agent_id=agent_id, private_key=private_key)
269
+
270
+ # ── Search ──────────────────────────────────────────────────────────────
271
+
272
+ def search(
273
+ self,
274
+ agent_id: str,
275
+ query: str,
276
+ limit: int = 10,
277
+ private_key: Optional[str] = None,
278
+ memory_type: Optional[str] = None,
279
+ mode: str = "hybrid",
280
+ order: Optional[str] = None,
281
+ resolve_conflicts: Optional[bool] = None,
282
+ include_ledger: Optional[bool] = None,
283
+ anchor_date: Optional[str] = None,
284
+ temporal_weight: Optional[float] = None,
285
+ graph: Optional[str] = None,
286
+ adaptive_diversity: Optional[bool] = None,
287
+ max_per_session: Optional[int] = None,
288
+ return_response: bool = False,
289
+ ) -> Union[List[dict], dict]:
290
+ """Search memories. mode is hybrid (default), semantic or keyword."""
291
+ params = {"agent_id": agent_id, "query": query, "limit": min(limit, 50), "mode": mode, "memory_type": memory_type}
292
+ if order:
293
+ params["order"] = order
294
+ if resolve_conflicts is not None:
295
+ params["resolve_conflicts"] = str(resolve_conflicts).lower()
296
+ if include_ledger is not None:
297
+ params["include_ledger"] = str(include_ledger).lower()
298
+ if anchor_date:
299
+ params["anchor_date"] = anchor_date
300
+ if temporal_weight is not None:
301
+ params["temporal_weight"] = str(temporal_weight)
302
+ if graph:
303
+ params["graph"] = graph
304
+ if adaptive_diversity is not None:
305
+ params["adaptive_diversity"] = str(adaptive_diversity).lower()
306
+ if max_per_session is not None:
307
+ params["max_per_session"] = str(max_per_session)
308
+ res = self._json("GET", "/search", params=params, agent_id=agent_id, private_key=private_key)
309
+ if return_response:
310
+ return res
311
+ return res.get("results", [])
312
+
313
+ def search_temporal(
314
+ self,
315
+ agent_id: str,
316
+ private_key: Optional[str],
317
+ query: str,
318
+ limit: int = 10,
319
+ after_date: Optional[str] = None,
320
+ before_date: Optional[str] = None,
321
+ after_event: Optional[str] = None,
322
+ before_event: Optional[str] = None,
323
+ session_id: Optional[str] = None,
324
+ atomic_only: Optional[bool] = None,
325
+ temporal_weight: float = 0.3,
326
+ ) -> dict:
327
+ """Search with date filters (RFC 3339) and a recency boost (0..1)."""
328
+ params = {
329
+ "agent_id": agent_id, "query": query, "limit": min(limit, 50),
330
+ "after_date": after_date, "before_date": before_date,
331
+ "after_event_date": after_event, "before_event_date": before_event,
332
+ "session_id": session_id, "atomic_only": atomic_only, "temporal_weight": temporal_weight,
333
+ }
334
+ return self._json("GET", "/search/temporal", params=params, agent_id=agent_id, private_key=private_key)
335
+
336
+ # ── Memory engine ───────────────────────────────────────────────────────
337
+
338
+ def reason(self, agent_id: str, private_key: Optional[str], query: str) -> dict:
339
+ """Answer from memory, following the knowledge graph for why/how questions."""
340
+ return self._json("POST", "/mee/reason", json_body={"query": query}, agent_id=agent_id, private_key=private_key)
341
+
342
+ def resolve_conflict(self, agent_id: str, private_key: Optional[str], memory_a_id: str, memory_b_id: str) -> dict:
343
+ """Pick the more trustworthy of two memories."""
344
+ body = {"memory_a_id": memory_a_id, "memory_b_id": memory_b_id}
345
+ return self._json("POST", "/mee/resolve", json_body=body, agent_id=agent_id, private_key=private_key)
346
+
347
+ def evolve(self, agent_id: str, private_key: Optional[str] = None) -> dict:
348
+ """Consolidate repeated episodes into semantic memories and link updates."""
349
+ return self._json("POST", "/mee/evolve", agent_id=agent_id, private_key=private_key)
350
+
351
+ def timeline(self, agent_id: str, private_key: Optional[str], memory_id: str) -> dict:
352
+ return self._json("GET", f"/mee/timeline/{memory_id}", agent_id=agent_id, private_key=private_key)
353
+
354
+ def memory_chain(self, agent_id: str, private_key: Optional[str], memory_id: str) -> dict:
355
+ return self._json("GET", f"/memory/chain/{memory_id}", agent_id=agent_id, private_key=private_key)
356
+
357
+ def analyze_conflicts(self, agent_id: str, private_key: Optional[str] = None) -> dict:
358
+ return self._json("GET", "/analyze/conflicts", agent_id=agent_id, private_key=private_key)
359
+
360
+ def generate_atoms(self, agent_id: str, private_key: Optional[str], text: str) -> dict:
361
+ """Split text into atomic facts (does not store them)."""
362
+ return self._json("POST", "/memory/generate-atoms", json_body={"chunk": text}, agent_id=agent_id, private_key=private_key)
363
+
364
+ def stats(self, agent_id: str, private_key: Optional[str] = None) -> dict:
365
+ return self._json("GET", "/stats/temporal", agent_id=agent_id, private_key=private_key)
366
+
367
+ def usage(self, agent_id: str, private_key: Optional[str] = None) -> dict:
368
+ return self._json("GET", "/usage", agent_id=agent_id, private_key=private_key)
369
+
370
+ # ── Files ───────────────────────────────────────────────────────────────
371
+
372
+ def upload_file(self, agent_id: str, private_key: Optional[str], file: FileInput) -> dict:
373
+ """Store a file and extract its text: {file_id, file_name, file_type, file_size, extracted_text}."""
374
+ return self._json("POST", "/upload", files={"file": _file(file)}, data={"agent_id": agent_id},
375
+ agent_id=agent_id, private_key=private_key)
376
+
377
+ def memory_from_file(self, agent_id: str, private_key: Optional[str], file_id: str,
378
+ memory_type: str = "semantic", visibility: str = "private") -> dict:
379
+ body = {"agent_id": agent_id, "file_id": file_id, "memory_type": memory_type, "visibility": visibility}
380
+ return self._json("POST", "/memory/from-file", json_body=body, agent_id=agent_id, private_key=private_key)
381
+
382
+ def upload_image(self, agent_id: str, private_key: Optional[str], file: FileInput) -> dict:
383
+ """Describe an image with vision and store the description as a memory."""
384
+ return self._json("POST", "/upload/image", files={"image": _file(file)}, agent_id=agent_id, private_key=private_key)
385
+
386
+ def upload_document(self, agent_id: str, private_key: Optional[str], file: FileInput) -> List[dict]:
387
+ """Store a PDF, Word, PowerPoint, Excel or text document as ~1,500-character
388
+ overlapping memories linked to the file."""
389
+ return self._json("POST", "/upload/document", files={"document": _file(file)}, agent_id=agent_id, private_key=private_key)
390
+
391
+ # ── Webhooks ────────────────────────────────────────────────────────────
392
+
393
+ def register_webhook(self, agent_id: str, private_key: Optional[str], url: str, event_type: str = "memory_created") -> None:
394
+ self.request("POST", "/hooks", json_body={"event_type": event_type, "url": url}, agent_id=agent_id, private_key=private_key)
395
+
396
+ def delete_webhook(self, agent_id: str, private_key: Optional[str], url: str, event_type: str = "memory_created") -> bool:
397
+ """Remove a webhook. Returns False if it was not registered."""
398
+ try:
399
+ self.request("DELETE", "/hooks", json_body={"event_type": event_type, "url": url}, agent_id=agent_id, private_key=private_key)
400
+ return True
401
+ except MemroError as e:
402
+ if e.status_code == 404:
403
+ return False
404
+ raise
405
+
406
+ def list_webhooks(self, agent_id: str, private_key: Optional[str] = None, event_type: str = "memory_created") -> List[str]:
407
+ return self._json("GET", f"/hooks/{event_type}", agent_id=agent_id, private_key=private_key)
408
+
409
+ # ── Coordination ────────────────────────────────────────────────────────
410
+
411
+ def coordination_claim(
412
+ self,
413
+ agent_id: str,
414
+ private_key: Optional[str],
415
+ resource: str,
416
+ intent: str = "",
417
+ session_id: Optional[str] = None,
418
+ ttl_seconds: Optional[int] = None,
419
+ ) -> dict:
420
+ body: Dict[str, Any] = {"resource": resource, "intent": intent}
421
+ if session_id:
422
+ body["session_id"] = session_id
423
+ if ttl_seconds:
424
+ body["ttl_seconds"] = ttl_seconds
425
+ return self._json("POST", "/coordination/claim", json_body=body, agent_id=agent_id, private_key=private_key)
426
+
427
+ def coordination_heartbeat(
428
+ self,
429
+ agent_id: str,
430
+ private_key: Optional[str],
431
+ resource: Optional[str] = None,
432
+ lease_id: Optional[str] = None,
433
+ ttl_seconds: Optional[int] = None,
434
+ session_id: Optional[str] = None,
435
+ ) -> dict:
436
+ body: Dict[str, Any] = {}
437
+ if session_id:
438
+ body["session_id"] = session_id
439
+ if resource:
440
+ body["resource"] = resource
441
+ if lease_id:
442
+ body["lease_id"] = lease_id
443
+ if ttl_seconds:
444
+ body["ttl_seconds"] = ttl_seconds
445
+ return self._json("POST", "/coordination/heartbeat", json_body=body, agent_id=agent_id, private_key=private_key)
446
+
447
+ def coordination_release(
448
+ self,
449
+ agent_id: str,
450
+ private_key: Optional[str],
451
+ resource: Optional[str] = None,
452
+ lease_id: Optional[str] = None,
453
+ status: str = "completed",
454
+ session_id: Optional[str] = None,
455
+ ) -> dict:
456
+ body: Dict[str, Any] = {"status": status}
457
+ if session_id:
458
+ body["session_id"] = session_id
459
+ if resource:
460
+ body["resource"] = resource
461
+ if lease_id:
462
+ body["lease_id"] = lease_id
463
+ return self._json("POST", "/coordination/release", json_body=body, agent_id=agent_id, private_key=private_key)
464
+
465
+ def coordination_handoff(
466
+ self,
467
+ agent_id: str,
468
+ private_key: Optional[str],
469
+ resource: Optional[str] = None,
470
+ lease_id: Optional[str] = None,
471
+ summary: str = "",
472
+ next_agent_id: Optional[str] = None,
473
+ session_id: Optional[str] = None,
474
+ ) -> dict:
475
+ body: Dict[str, Any] = {"summary": summary}
476
+ if session_id:
477
+ body["session_id"] = session_id
478
+ if resource:
479
+ body["resource"] = resource
480
+ if lease_id:
481
+ body["lease_id"] = lease_id
482
+ if next_agent_id:
483
+ body["next_agent_id"] = next_agent_id
484
+ return self._json("POST", "/coordination/handoff", json_body=body, agent_id=agent_id, private_key=private_key)
485
+
486
+ def coordination_check(
487
+ self,
488
+ agent_id: str,
489
+ private_key: Optional[str],
490
+ resource: str,
491
+ intent: str = "",
492
+ session_id: Optional[str] = None,
493
+ ) -> dict:
494
+ body: Dict[str, Any] = {"resource": resource, "intent": intent}
495
+ if session_id:
496
+ body["session_id"] = session_id
497
+ return self._json("POST", "/coordination/check", json_body=body, agent_id=agent_id, private_key=private_key)
498
+
499
+ def coordination_active(
500
+ self,
501
+ agent_id: str,
502
+ private_key: Optional[str] = None,
503
+ resource: Optional[str] = None,
504
+ ) -> dict:
505
+ params = {"resource": resource} if resource else None
506
+ return self._json("GET", "/coordination/active", params=params, agent_id=agent_id, private_key=private_key)
507
+
508
+ def coordination_intent(
509
+ self,
510
+ agent_id: str,
511
+ private_key: Optional[str],
512
+ resource: str,
513
+ intent: str,
514
+ ttl_seconds: Optional[int] = None,
515
+ session_id: Optional[str] = None,
516
+ ) -> dict:
517
+ body: Dict[str, Any] = {"resource": resource, "intent": intent}
518
+ if session_id:
519
+ body["session_id"] = session_id
520
+ if ttl_seconds:
521
+ body["ttl_seconds"] = ttl_seconds
522
+ return self._json("POST", "/coordination/intent", json_body=body, agent_id=agent_id, private_key=private_key)
523
+
524
+
525
+ def _param(v: Any) -> str:
526
+ if isinstance(v, bool):
527
+ return "true" if v else "false"
528
+ return str(v)
529
+
530
+
531
+ def _retry_delay(resp: Response, attempt: int) -> float:
532
+ try:
533
+ return min(float(resp.headers.get("Retry-After", "")), 30.0)
534
+ except ValueError:
535
+ return 0.5 * (2 ** attempt)
536
+
537
+
538
+ def _file(file: FileInput) -> Tuple[str, bytes, str]:
539
+ if isinstance(file, tuple):
540
+ name, data = file[0], file[1]
541
+ ctype = file[2] if len(file) > 2 else (mimetypes.guess_type(name)[0] or "application/octet-stream")
542
+ return name, data, ctype
543
+ path = os.fspath(file)
544
+ with open(path, "rb") as f:
545
+ data = f.read()
546
+ name = os.path.basename(path)
547
+ return name, data, mimetypes.guess_type(name)[0] or "application/octet-stream"
memro/crypto.py ADDED
@@ -0,0 +1,110 @@
1
+ """
2
+ ed25519 cryptographic operations for the memro protocol.
3
+ Uses PyNaCl (libsodium bindings).
4
+ """
5
+ import hashlib
6
+ import time
7
+ from typing import Tuple
8
+
9
+ try:
10
+ import nacl.signing
11
+ import nacl.encoding
12
+ except ImportError:
13
+ raise ImportError(
14
+ "PyNaCl is required: pip install pynacl"
15
+ )
16
+
17
+
18
+ def generate_keypair() -> Tuple[str, str]:
19
+ """
20
+ Generate a new ed25519 keypair.
21
+ Returns (public_key_hex, private_key_hex).
22
+ The public key hex is the agent_id.
23
+ """
24
+ signing_key = nacl.signing.SigningKey.generate()
25
+ verify_key = signing_key.verify_key
26
+
27
+ private_key_hex = signing_key.encode(encoder=nacl.encoding.HexEncoder).decode()
28
+ public_key_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder).decode()
29
+
30
+ return public_key_hex, private_key_hex
31
+
32
+
33
+ def _signing_key(private_key_hex: str) -> "nacl.signing.SigningKey":
34
+ try:
35
+ private_key_bytes = bytes.fromhex(private_key_hex)
36
+ except ValueError:
37
+ raise ValueError("Invalid private key: must be a 64-character hexadecimal string.")
38
+ return nacl.signing.SigningKey(private_key_bytes)
39
+
40
+
41
+ def sign_request(private_key_hex: str, method: str, path_and_query: str, body: bytes) -> dict:
42
+ """
43
+ Sign a request with the v2 scheme, which binds the method, path and query
44
+ as well as the body: "<timestamp>\n<METHOD>\n<path?query>\n<body>".
45
+ Returns the X-Signature, X-Timestamp and X-Signature-Version headers.
46
+ """
47
+ timestamp = str(int(time.time()))
48
+ payload = f"{timestamp}\n{method.upper()}\n{path_and_query}\n".encode() + body
49
+ signature = _signing_key(private_key_hex).sign(payload).signature.hex()
50
+ return {"X-Signature": signature, "X-Timestamp": timestamp, "X-Signature-Version": "2"}
51
+
52
+
53
+ def sign_body(private_key_hex: str, body: bytes) -> dict:
54
+ """
55
+ Legacy v1 signature over timestamp + body only. Prefer sign_request,
56
+ which also covers the method, path and query string.
57
+ """
58
+ try:
59
+ private_key_bytes = bytes.fromhex(private_key_hex)
60
+ except ValueError:
61
+ raise ValueError("Invalid private key: must be a 64-character hexadecimal string.")
62
+
63
+ signing_key = nacl.signing.SigningKey(private_key_bytes)
64
+
65
+ timestamp = str(int(time.time()))
66
+
67
+ # Robust Payload: TIMESTAMP + BODY
68
+ payload = timestamp.encode() + body
69
+
70
+ # Sign the payload
71
+ signed = signing_key.sign(payload)
72
+ signature_hex = signed.signature.hex()
73
+
74
+ return {
75
+ "X-Signature": signature_hex,
76
+ "X-Timestamp": timestamp,
77
+ }
78
+
79
+
80
+ POW_PREFIX = "memro-identity-v1"
81
+
82
+
83
+ def _leading_zero_bits(digest: bytes) -> int:
84
+ n = 0
85
+ for byte in digest:
86
+ if byte == 0:
87
+ n += 8
88
+ continue
89
+ return n + 8 - byte.bit_length()
90
+ return n
91
+
92
+
93
+ def solve_pow(public_key: str, difficulty: int, timestamp: int = None) -> Tuple[int, str]:
94
+ """
95
+ Proof-of-work for registering an agent (ADR 0013): a nonce whose SHA-256
96
+ over "memro-identity-v1:<public_key>:<timestamp>:<nonce>" starts with
97
+ `difficulty` zero bits. Returns (timestamp, nonce). Difficulty 20 takes
98
+ about a second.
99
+ """
100
+ if timestamp is None:
101
+ timestamp = int(time.time())
102
+ base = hashlib.sha256(f"{POW_PREFIX}:{public_key}:{timestamp}:".encode())
103
+ i = 0
104
+ while True:
105
+ nonce = format(i, "x")
106
+ h = base.copy()
107
+ h.update(nonce.encode())
108
+ if _leading_zero_bits(h.digest()) >= difficulty:
109
+ return timestamp, nonce
110
+ i += 1
File without changes