beeply-native 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.
@@ -0,0 +1,10 @@
1
+ from .client import NativeSupportClient, SupportError
2
+ from .store import CogineWorkStore, StateStore, StoreError
3
+
4
+ __all__ = [
5
+ "NativeSupportClient",
6
+ "SupportError",
7
+ "CogineWorkStore",
8
+ "StateStore",
9
+ "StoreError",
10
+ ]
@@ -0,0 +1,760 @@
1
+ """Small customer-only adapter. The server owns identity, authorization and facts.
2
+
3
+ One client owns a store within one native process/event loop. The lifecycle lock
4
+ only orders identity changes; ordinary reads and message requests do not hold it.
5
+ There are no background subscriptions, automatic sends, retries or refresh jobs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import copy
12
+ import secrets
13
+ import hashlib
14
+ from typing import Any, Literal
15
+ from urllib.parse import quote, urlsplit
16
+ from uuid import uuid4
17
+
18
+ import httpx
19
+
20
+ from .store import StateStore
21
+
22
+
23
+ def segment(value: str) -> str:
24
+ return quote(value, safe="")
25
+
26
+
27
+ class SupportError(RuntimeError):
28
+ def __init__(
29
+ self,
30
+ code: str,
31
+ *,
32
+ status: int = 0,
33
+ operation_id: str | None = None,
34
+ retry_after: int | None = None,
35
+ ):
36
+ self.code, self.status, self.operation_id, self.retry_after = (
37
+ code,
38
+ status,
39
+ operation_id,
40
+ retry_after,
41
+ )
42
+ super().__init__(code)
43
+
44
+
45
+ class NativeSupportClient:
46
+ def __init__(
47
+ self,
48
+ api_origin: str,
49
+ product_id: str,
50
+ store: StateStore,
51
+ *,
52
+ transport: httpx.AsyncBaseTransport | None = None,
53
+ ):
54
+ origin = urlsplit(api_origin)
55
+ if (
56
+ origin.username
57
+ or origin.password
58
+ or origin.query
59
+ or origin.fragment
60
+ or origin.path not in ("", "/")
61
+ or not origin.hostname
62
+ ):
63
+ raise ValueError("API_ORIGIN_REQUIRED")
64
+ if origin.scheme != "https" and not (
65
+ origin.scheme == "http"
66
+ and origin.hostname in ("127.0.0.1", "localhost", "::1")
67
+ ):
68
+ raise ValueError("TLS_REQUIRED")
69
+ self.api_origin, self.product_id, self._store = (
70
+ api_origin.rstrip("/"),
71
+ product_id,
72
+ store,
73
+ )
74
+ saved = store.load()
75
+ self._state = (
76
+ saved
77
+ if saved is not None
78
+ else {
79
+ "version": 1,
80
+ "origin": self.api_origin,
81
+ "productId": product_id,
82
+ "token": None,
83
+ "operations": {},
84
+ "drafts": {},
85
+ "recovery": None,
86
+ }
87
+ )
88
+ if (
89
+ self._state.get("version") != 1
90
+ or self._state.get("origin") != self.api_origin
91
+ or self._state.get("productId") != product_id
92
+ ):
93
+ raise SupportError("STORE_SCOPE_MISMATCH")
94
+ self._http = httpx.AsyncClient(
95
+ base_url=self.api_origin,
96
+ transport=transport,
97
+ follow_redirects=False,
98
+ timeout=30,
99
+ )
100
+ self._session: dict[str, Any] | None = None
101
+ self._scopes: set[str] = set()
102
+ self._epoch = 0
103
+ self._checking_restore = False
104
+ self._closed = False
105
+ self._lifecycle = asyncio.Lock()
106
+ self._auth = f"/auth/customer/products/{segment(product_id)}"
107
+ self._api = f"/v1/customer/products/{segment(product_id)}"
108
+
109
+ def _save(self, **changes: Any) -> None:
110
+ # A failed disk write cannot promote an in-memory credential or command.
111
+ updated = {**self._state, **changes}
112
+ self._store.save(updated)
113
+ self._state = updated
114
+
115
+ def _hide(self) -> None:
116
+ self._epoch += 1
117
+ self._session = None
118
+ self._scopes.clear()
119
+
120
+ def local_status(self) -> dict[str, Any]:
121
+ transaction = self._state["recovery"]
122
+ restoring = self._checking_restore or (
123
+ transaction is not None and transaction["request"]["purpose"] == "restore"
124
+ )
125
+ return {
126
+ "hasSavedSession": bool(self._state["token"]),
127
+ "verifiedSession": None if restoring else copy.deepcopy(self._session),
128
+ "recovery": (
129
+ None
130
+ if transaction is None
131
+ else {
132
+ "purpose": transaction["request"]["purpose"],
133
+ "operationId": transaction["request"]["operationId"],
134
+ "challenge": copy.deepcopy(transaction["challenge"]),
135
+ "verificationPending": transaction["verificationId"] is not None,
136
+ }
137
+ ),
138
+ }
139
+
140
+ def _ready(self) -> dict[str, Any]:
141
+ transaction = self._state["recovery"]
142
+ if self._checking_restore or (
143
+ transaction is not None and transaction["request"]["purpose"] == "restore"
144
+ ):
145
+ raise SupportError("RECOVERY_IN_PROGRESS")
146
+ if self._session is None:
147
+ raise SupportError("SESSION_REQUIRED")
148
+ return self._session
149
+
150
+ async def _call(
151
+ self,
152
+ method: str,
153
+ path: str,
154
+ *,
155
+ body: Any = None,
156
+ auth: bool = True,
157
+ recovery: bool = False,
158
+ operation_id: str | None = None,
159
+ content: bytes | None = None,
160
+ upload_token: str | None = None,
161
+ binary: bool = False,
162
+ ) -> tuple[Any, str | None]:
163
+ if self._closed:
164
+ raise SupportError("CLIENT_CLOSED")
165
+ epoch = self._epoch
166
+ bearer = auth and not recovery
167
+ headers = {"Accept": "application/json"}
168
+ if recovery:
169
+ transaction = self._state["recovery"]
170
+ if transaction is None:
171
+ raise SupportError("RECOVERY_REQUIRED")
172
+ if transaction["request"]["purpose"] == "bind":
173
+ bearer = True
174
+ headers.update(
175
+ {
176
+ "Authorization": f"Bearer {self._state['token']}",
177
+ "X-Recovery-Handle": transaction["handle"],
178
+ }
179
+ )
180
+ else:
181
+ headers["Authorization"] = f"Recovery {transaction['handle']}"
182
+ elif auth:
183
+ if not self._state["token"]:
184
+ raise SupportError("SESSION_REQUIRED")
185
+ headers["Authorization"] = f"Bearer {self._state['token']}"
186
+ if upload_token:
187
+ headers["X-Upload-Token"] = upload_token
188
+ if content is not None:
189
+ headers["Content-Type"] = "application/octet-stream"
190
+ try:
191
+ response = await self._http.request(
192
+ method,
193
+ path,
194
+ headers=headers,
195
+ **({"content": content} if content is not None else {"json": body}),
196
+ )
197
+ except httpx.TransportError:
198
+ raise SupportError(
199
+ "REQUEST_UNCERTAIN" if method != "GET" else "CONNECTION_UNAVAILABLE",
200
+ operation_id=operation_id,
201
+ ) from None
202
+ if epoch != self._epoch:
203
+ raise SupportError("SESSION_CHANGED", operation_id=operation_id)
204
+ if binary and response.is_success:
205
+ return response.content, None
206
+ try:
207
+ data = None if response.status_code == 204 else response.json()
208
+ except ValueError:
209
+ raise SupportError(
210
+ "REQUEST_UNCERTAIN",
211
+ status=response.status_code,
212
+ operation_id=operation_id,
213
+ ) from None
214
+ if not response.is_success:
215
+ error = data.get("error", {}) if isinstance(data, dict) else {}
216
+ code = (
217
+ error.get("code", "REQUEST_FAILED")
218
+ if isinstance(error, dict)
219
+ else "REQUEST_FAILED"
220
+ )
221
+ if response.status_code == 401 and bearer:
222
+ self._hide()
223
+ retry = response.headers.get("Retry-After", "")
224
+ raise SupportError(
225
+ code,
226
+ status=response.status_code,
227
+ operation_id=operation_id,
228
+ retry_after=int(retry) if retry.isdecimal() else None,
229
+ )
230
+ return data, response.headers.get("Set-Auth-Token")
231
+
232
+ async def _adopt(self, token: str | None) -> dict[str, Any]:
233
+ if not token:
234
+ raise SupportError("CREDENTIAL_NOT_DELIVERED")
235
+ self._hide()
236
+ self._save(token=token)
237
+ return await self._resume()
238
+
239
+ async def _resume(self) -> dict[str, Any]:
240
+ data, _ = await self._call("GET", self._auth + "/session")
241
+ if data["productId"] != self.product_id:
242
+ self._hide()
243
+ raise SupportError("SESSION_PRODUCT_MISMATCH")
244
+ if self._session and (
245
+ self._session["viewerKey"],
246
+ self._session["accessRevision"],
247
+ ) != (data["viewerKey"], data["accessRevision"]):
248
+ self._hide()
249
+ self._session = data
250
+ self._scopes.add(data["defaultCustomerScopeKey"])
251
+ return copy.deepcopy(data)
252
+
253
+ async def resume(self) -> dict[str, Any]:
254
+ async with self._lifecycle:
255
+ transaction = self._state["recovery"]
256
+ if (
257
+ transaction is not None
258
+ and transaction["request"]["purpose"] == "restore"
259
+ ):
260
+ raise SupportError("RECOVERY_IN_PROGRESS")
261
+ return await self._resume()
262
+
263
+ async def create_guest(self) -> dict[str, Any]:
264
+ async with self._lifecycle:
265
+ if self._state["recovery"] is not None:
266
+ raise SupportError("RECOVERY_IN_PROGRESS")
267
+ if self._state["token"]:
268
+ raise SupportError("EXISTING_SESSION")
269
+ _, token = await self._call(
270
+ "POST",
271
+ self._auth + "/sessions/guest",
272
+ body={"transport": "native"},
273
+ auth=False,
274
+ )
275
+ return await self._adopt(token)
276
+
277
+ async def refresh(self) -> dict[str, Any]:
278
+ async with self._lifecycle:
279
+ self._ready()
280
+ await self._call("POST", self._auth + "/session/refresh")
281
+ return await self._resume()
282
+
283
+ async def logout(self) -> None:
284
+ async with self._lifecycle:
285
+ self._hide()
286
+ if self._state["token"]:
287
+ try:
288
+ await self._call("DELETE", self._auth + "/session")
289
+ except SupportError as error:
290
+ if error.status != 401:
291
+ raise
292
+ self._save(token=None, recovery=None)
293
+
294
+ async def close(self) -> None:
295
+ self._closed = True
296
+ self._hide()
297
+ await self._http.aclose()
298
+
299
+ async def verify_scope(self, scope_key: str) -> None:
300
+ self._ready()
301
+ await self._call("GET", self._api + f"/scopes/{segment(scope_key)}")
302
+ self._scopes.add(scope_key)
303
+
304
+ def save_draft(self, scope_key: str, draft_id: str, text: str) -> None:
305
+ self._ready()
306
+ if scope_key not in self._scopes:
307
+ raise SupportError("SCOPE_NOT_VERIFIED")
308
+ drafts = copy.deepcopy(self._state["drafts"])
309
+ drafts.setdefault(scope_key, {})[draft_id] = text
310
+ self._save(drafts=drafts)
311
+
312
+ async def draft(self, scope_key: str, draft_id: str) -> str:
313
+ await self.verify_scope(scope_key)
314
+ return self._state["drafts"].get(scope_key, {}).get(draft_id, "")
315
+
316
+ def prepare_request(
317
+ self,
318
+ text: str,
319
+ *,
320
+ scope_key: str | None = None,
321
+ subject: str | None = None,
322
+ attachment_ids: list[str] | None = None,
323
+ ) -> str:
324
+ session = self._ready()
325
+ scope = scope_key or session["defaultCustomerScopeKey"]
326
+ if scope not in self._scopes:
327
+ raise SupportError("SCOPE_NOT_VERIFIED")
328
+ operation_id = str(uuid4())
329
+ body = {
330
+ "operationId": operation_id,
331
+ "customerScopeKey": scope,
332
+ "text": text,
333
+ "attachmentIds": list(attachment_ids or []),
334
+ }
335
+ if subject is not None:
336
+ body["subject"] = subject
337
+ return self._prepare(operation_id, scope, self._api + "/conversations", body)
338
+
339
+ async def prepare_message(
340
+ self,
341
+ conversation_id: str,
342
+ text: str,
343
+ *,
344
+ attachment_ids: list[str] | None = None,
345
+ ) -> str:
346
+ conversation = await self.conversation(conversation_id)
347
+ operation_id = str(uuid4())
348
+ return self._prepare(
349
+ operation_id,
350
+ conversation["customerScopeKey"],
351
+ f"/v1/customer/conversations/{segment(conversation_id)}/messages",
352
+ {
353
+ "operationId": operation_id,
354
+ "text": text,
355
+ "attachmentIds": list(attachment_ids or []),
356
+ },
357
+ conversation_id,
358
+ )
359
+
360
+ async def prepare_attachment(
361
+ self,
362
+ name: str,
363
+ content: bytes,
364
+ *,
365
+ mime_type: str = "application/octet-stream",
366
+ scope_key: str | None = None,
367
+ conversation_id: str | None = None,
368
+ ) -> str:
369
+ session = self._ready()
370
+ scope = scope_key or session["defaultCustomerScopeKey"]
371
+ if conversation_id:
372
+ scope = (await self.conversation(conversation_id))["customerScopeKey"]
373
+ if scope not in self._scopes:
374
+ raise SupportError("SCOPE_NOT_VERIFIED")
375
+ if len(content) > 5 * 1024 * 1024:
376
+ raise SupportError("ATTACHMENT_TOO_LARGE")
377
+ operation_id = str(uuid4())
378
+ body = {
379
+ "operationId": operation_id,
380
+ "customerScopeKey": scope,
381
+ "name": name,
382
+ "mimeType": mime_type,
383
+ "sizeBytes": len(content),
384
+ "sha256": hashlib.sha256(content).hexdigest(),
385
+ }
386
+ if conversation_id:
387
+ body["conversationId"] = conversation_id
388
+ return self._prepare(operation_id, scope, self._api + "/attachments", body)
389
+
390
+ async def attachment(self, attachment_id: str) -> dict[str, Any]:
391
+ self._ready()
392
+ result, _ = await self._call(
393
+ "GET", f"/v1/customer/attachments/{segment(attachment_id)}"
394
+ )
395
+ return result
396
+
397
+ async def upload_attachment(self, attachment_id: str, content: bytes) -> None:
398
+ # Explicit bytes only. No device-path reading, background file collection,
399
+ # or raw content/token persisted in the host Secret Store.
400
+ if len(content) > 5 * 1024 * 1024:
401
+ raise SupportError("ATTACHMENT_TOO_LARGE")
402
+ upload = await self.attachment(attachment_id)
403
+ if upload["state"] == "ready":
404
+ return
405
+ if upload["state"] == "expired":
406
+ raise SupportError("UPLOAD_EXPIRED", status=409)
407
+ await self._call(
408
+ "PUT",
409
+ f"/v1/customer/attachments/{segment(attachment_id)}/content",
410
+ content=content,
411
+ upload_token=upload["uploadToken"],
412
+ )
413
+
414
+ async def confirm_attachment(self, attachment_id: str) -> dict[str, Any]:
415
+ self._ready()
416
+ result, _ = await self._call(
417
+ "POST",
418
+ f"/v1/customer/attachments/{segment(attachment_id)}/confirm",
419
+ body={},
420
+ )
421
+ return result
422
+
423
+ async def download_attachment(self, attachment_id: str) -> bytes:
424
+ self._ready()
425
+ result, _ = await self._call(
426
+ "GET",
427
+ f"/v1/customer/attachments/{segment(attachment_id)}/content",
428
+ binary=True,
429
+ )
430
+ return result
431
+
432
+ async def attachment_text(self, attachment_id: str) -> str:
433
+ self._ready()
434
+ result, _ = await self._call(
435
+ "GET", f"/v1/customer/attachments/{segment(attachment_id)}/text"
436
+ )
437
+ return result["text"]
438
+
439
+ async def prepare_result(
440
+ self,
441
+ conversation_id: str,
442
+ outcome: Literal["confirmed_resolved", "still_unresolved"],
443
+ ) -> str:
444
+ conversation = await self.conversation(conversation_id)
445
+ operation_id = str(uuid4())
446
+ return self._prepare(
447
+ operation_id,
448
+ conversation["customerScopeKey"],
449
+ f"/v1/customer/conversations/{segment(conversation_id)}/result",
450
+ {
451
+ "operationId": operation_id,
452
+ "serviceRound": conversation["serviceRound"],
453
+ "resultVersion": conversation["resultVersion"],
454
+ "outcome": outcome,
455
+ },
456
+ conversation_id,
457
+ )
458
+
459
+ def _prepare(
460
+ self,
461
+ operation_id: str,
462
+ scope: str,
463
+ path: str,
464
+ body: dict[str, Any],
465
+ conversation_id: str | None = None,
466
+ ) -> str:
467
+ operations = {
468
+ **self._state["operations"],
469
+ operation_id: {
470
+ "scope": scope,
471
+ "path": path,
472
+ "body": body,
473
+ "conversationId": conversation_id,
474
+ },
475
+ }
476
+ self._save(operations=operations)
477
+ return operation_id
478
+
479
+ async def pending_operations(self) -> list[dict[str, Any]]:
480
+ self._ready()
481
+ visible = []
482
+ for operation_id, command in list(self._state["operations"].items()):
483
+ try:
484
+ await self.verify_scope(command["scope"])
485
+ except SupportError as error:
486
+ if error.status in (403, 404):
487
+ continue
488
+ raise
489
+ if operation_id not in self._state["operations"]:
490
+ continue
491
+ visible.append(
492
+ {
493
+ "operationId": operation_id,
494
+ "customerScopeKey": command["scope"],
495
+ "conversationId": command["conversationId"],
496
+ "payload": copy.deepcopy(command["body"]),
497
+ "rejection": command.get("rejection"),
498
+ }
499
+ )
500
+ return visible
501
+
502
+ def _pending(self, operation_id: str) -> dict[str, Any]:
503
+ command = self._state["operations"].get(operation_id)
504
+ if command is None:
505
+ raise SupportError("OPERATION_NOT_PENDING", operation_id=operation_id)
506
+ return command
507
+
508
+ def discard_rejected_operation(self, operation_id: str) -> None:
509
+ self._ready()
510
+ command = self._pending(operation_id)
511
+ if command["scope"] not in self._scopes:
512
+ raise SupportError("SCOPE_NOT_VERIFIED")
513
+ if not command.get("rejection"):
514
+ raise SupportError("OPERATION_UNCERTAIN", operation_id=operation_id)
515
+ self._save(
516
+ operations={
517
+ k: v for k, v in self._state["operations"].items() if k != operation_id
518
+ }
519
+ )
520
+
521
+ async def send_operation(self, operation_id: str) -> dict[str, Any]:
522
+ self._ready()
523
+ command = self._pending(operation_id)
524
+ try:
525
+ result, _ = await self._call(
526
+ "POST", command["path"], body=command["body"], operation_id=operation_id
527
+ )
528
+ except SupportError as error:
529
+ # Only deterministic pre-acceptance field failures may be discarded.
530
+ # Auth, other conflicts, rate limits and unknown outcomes keep the journal.
531
+ if (
532
+ error.status == 422
533
+ and error.code
534
+ in (
535
+ "INVALID_TEXT",
536
+ "INVALID_ATTACHMENT",
537
+ "INVALID_REQUEST",
538
+ "ATTACHMENT_TYPE_UNSUPPORTED",
539
+ "ATTACHMENT_TOO_LARGE",
540
+ )
541
+ ) or (error.status == 409 and error.code == "ATTACHMENT_CHANGED"):
542
+ self._save(
543
+ operations={
544
+ **self._state["operations"],
545
+ operation_id: {**command, "rejection": error.code},
546
+ }
547
+ )
548
+ raise
549
+ operations = {
550
+ k: v for k, v in self._state["operations"].items() if k != operation_id
551
+ }
552
+ self._save(operations=operations)
553
+ return result
554
+
555
+ async def operation(self, operation_id: str) -> dict[str, Any]:
556
+ self._ready()
557
+ command = self._pending(operation_id)
558
+ params = {"customerScopeKey": command["scope"]}
559
+ if command["conversationId"]:
560
+ params["conversationId"] = command["conversationId"]
561
+ query = str(httpx.QueryParams(params))
562
+ result, _ = await self._call(
563
+ "GET",
564
+ self._api + f"/operations/{segment(operation_id)}?{query}",
565
+ operation_id=operation_id,
566
+ )
567
+ # Querying not_received never resends or changes the original command.
568
+ if result["state"] == "accepted":
569
+ self._save(
570
+ operations={
571
+ k: v
572
+ for k, v in self._state["operations"].items()
573
+ if k != operation_id
574
+ }
575
+ )
576
+ return result
577
+
578
+ async def conversations(self, *, cursor: str | None = None) -> dict[str, Any]:
579
+ self._ready()
580
+ suffix = "?" + str(httpx.QueryParams({"cursor": cursor})) if cursor else ""
581
+ return (await self._call("GET", self._api + "/conversations" + suffix))[0]
582
+
583
+ async def conversation(self, conversation_id: str) -> dict[str, Any]:
584
+ self._ready()
585
+ result, _ = await self._call(
586
+ "GET", f"/v1/customer/conversations/{segment(conversation_id)}"
587
+ )
588
+ self._scopes.add(result["customerScopeKey"])
589
+ return result
590
+
591
+ async def messages(
592
+ self,
593
+ conversation_id: str,
594
+ *,
595
+ direction: Literal["latest", "before", "after"] = "latest",
596
+ cursor: str | None = None,
597
+ ) -> dict[str, Any]:
598
+ self._ready()
599
+ params = {"direction": direction}
600
+ if cursor is not None:
601
+ params["cursor"] = cursor
602
+ return (
603
+ await self._call(
604
+ "GET",
605
+ f"/v1/customer/conversations/{segment(conversation_id)}/messages?{httpx.QueryParams(params)}",
606
+ )
607
+ )[0]
608
+
609
+ async def mark_read(self, conversation_id: str, visible_cursor: str) -> None:
610
+ self._ready()
611
+ await self._call(
612
+ "POST",
613
+ f"/v1/customer/conversations/{segment(conversation_id)}/read",
614
+ body={"cursor": visible_cursor},
615
+ )
616
+
617
+ async def start_recovery(
618
+ self, purpose: Literal["bind", "restore"], email: str
619
+ ) -> dict[str, Any]:
620
+ async with self._lifecycle:
621
+ if self._state["recovery"] is not None:
622
+ raise SupportError("RECOVERY_IN_PROGRESS")
623
+ if purpose == "bind":
624
+ self._ready()
625
+ elif self._state["token"] and self._session is None:
626
+ try:
627
+ await self._resume()
628
+ except SupportError as error:
629
+ if error.status != 401:
630
+ raise
631
+ if purpose == "restore":
632
+ # Stop new business writes before checking an unbound guest.
633
+ # Existing in-flight writes keep their journal on SESSION_CHANGED.
634
+ self._epoch += 1
635
+ self._checking_restore = True
636
+ try:
637
+ if self._session and not self._session["recoveryBound"]:
638
+ if (
639
+ any(
640
+ text.strip()
641
+ for scope in self._scopes
642
+ for text in self._state["drafts"]
643
+ .get(scope, {})
644
+ .values()
645
+ )
646
+ or any(
647
+ c["scope"] in self._scopes
648
+ for c in self._state["operations"].values()
649
+ )
650
+ or (await self._call("GET", self._api + "/conversations"))[
651
+ 0
652
+ ]["items"]
653
+ ):
654
+ raise SupportError("BIND_CURRENT_SCOPE_FIRST")
655
+ finally:
656
+ self._checking_restore = False
657
+ operation_id = str(uuid4())
658
+ transaction = {
659
+ "handle": secrets.token_urlsafe(32),
660
+ "request": {
661
+ "operationId": operation_id,
662
+ "purpose": purpose,
663
+ "email": email,
664
+ "transport": "native",
665
+ },
666
+ "challenge": None,
667
+ "verificationId": None,
668
+ }
669
+ self._save(recovery=transaction)
670
+ return await self._send_recovery()
671
+
672
+ async def _send_recovery(self) -> dict[str, Any]:
673
+ transaction = self._state["recovery"]
674
+ if transaction is None:
675
+ raise SupportError("RECOVERY_REQUIRED")
676
+ result, _ = await self._call(
677
+ "POST",
678
+ self._auth + "/recovery/challenges",
679
+ body=transaction["request"],
680
+ recovery=True,
681
+ operation_id=transaction["request"]["operationId"],
682
+ )
683
+ self._save(recovery={**transaction, "challenge": result})
684
+ return copy.deepcopy(result)
685
+
686
+ async def recovery_status(self) -> dict[str, Any]:
687
+ async with self._lifecycle:
688
+ transaction = self._state["recovery"]
689
+ if transaction is None:
690
+ raise SupportError("RECOVERY_REQUIRED")
691
+ try:
692
+ result, _ = await self._call(
693
+ "GET",
694
+ self._auth
695
+ + f"/recovery/operations/{segment(transaction['request']['operationId'])}",
696
+ recovery=True,
697
+ )
698
+ except SupportError as error:
699
+ if error.code == "RECOVERY_HANDLE_EXPIRED":
700
+ self._save(recovery=None)
701
+ raise
702
+ state = result.get("state")
703
+ if state == "bound":
704
+ await self._resume()
705
+ if state in ("bound", "no_recoverable_records"):
706
+ self._save(recovery=None)
707
+ elif "challengeId" in result:
708
+ self._save(recovery={**transaction, "challenge": result})
709
+ return copy.deepcopy(result)
710
+
711
+ async def retry_recovery(self) -> dict[str, Any]:
712
+ async with self._lifecycle:
713
+ return await self._send_recovery()
714
+
715
+ async def verify_recovery(self, code: str) -> dict[str, Any]:
716
+ async with self._lifecycle:
717
+ transaction = self._state["recovery"]
718
+ if transaction is None or transaction["challenge"] is None:
719
+ raise SupportError("RECOVERY_REQUIRED")
720
+ if transaction["request"]["purpose"] == "restore":
721
+ self._hide()
722
+ verification_id = transaction["verificationId"] or str(uuid4())
723
+ self._save(recovery={**transaction, "verificationId": verification_id})
724
+ try:
725
+ result, token = await self._call(
726
+ "POST",
727
+ self._auth
728
+ + f"/recovery/challenges/{segment(transaction['challenge']['challengeId'])}/verify",
729
+ body={"operationId": verification_id, "code": code},
730
+ recovery=True,
731
+ operation_id=verification_id,
732
+ )
733
+ except SupportError as error:
734
+ if error.code == "RECOVERY_HANDLE_EXPIRED":
735
+ self._save(recovery=None)
736
+ elif error.code in ("OTP_INVALID", "OTP_EXPIRED", "OTP_LIMITED") or (
737
+ error.status == 422
738
+ and error.code == "INVALID_REQUEST"
739
+ and transaction["verificationId"] is None
740
+ ):
741
+ # A malformed retry cannot settle an earlier unknown attempt.
742
+ self._save(
743
+ recovery={**self._state["recovery"], "verificationId": None}
744
+ )
745
+ raise
746
+ if result["kind"] == "restored":
747
+ await self._adopt(token)
748
+ elif result["kind"] == "bound":
749
+ await self._resume()
750
+ self._save(recovery=None)
751
+ return result
752
+
753
+ def cancel_recovery(self) -> None:
754
+ # Local cancellation neither revokes the current session nor moves drafts.
755
+ if self._lifecycle.locked():
756
+ raise SupportError("IDENTITY_CHANGE_IN_PROGRESS")
757
+ transaction = self._state["recovery"]
758
+ if transaction is not None and transaction["verificationId"] is not None:
759
+ raise SupportError("RECOVERY_RESULT_UNCERTAIN")
760
+ self._save(recovery=None)
beeply_native/store.py ADDED
@@ -0,0 +1,72 @@
1
+ """Trusted native-process persistence. Never expose this interface to a renderer."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any, Protocol
8
+
9
+
10
+ class StoreError(RuntimeError):
11
+ pass
12
+
13
+
14
+ class StateStore(Protocol):
15
+ def load(self) -> dict[str, Any] | None:
16
+ ...
17
+
18
+ def save(self, state: dict[str, Any]) -> None:
19
+ """Return only after the atomic durable write succeeds."""
20
+ ...
21
+
22
+
23
+ class CogineWorkStore:
24
+ """Reuse CogineWork's key ownership, strict decryption and atomic writer.
25
+
26
+ Each API origin/product gets a separate sealed file. No new master key,
27
+ credential system or plaintext fallback is introduced here.
28
+ """
29
+
30
+ def __init__(self, api_origin: str, product_id: str, *, path: Path | None = None):
31
+ from coginework.constant import SECRET_DIR
32
+ from coginework.config.config import write_json_atomically
33
+ from coginework.security.secret_store import encrypt, decrypt_existing
34
+
35
+ key = hashlib.sha256(
36
+ f"{api_origin.rstrip('/')}\n{product_id}".encode()
37
+ ).hexdigest()
38
+ self.path = path or SECRET_DIR / "beeply" / f"{key}.json"
39
+ self._encrypt, self._decrypt, self._write = (
40
+ encrypt,
41
+ decrypt_existing,
42
+ write_json_atomically,
43
+ )
44
+
45
+ def load(self) -> dict[str, Any] | None:
46
+ if not self.path.exists():
47
+ return None
48
+ try:
49
+ envelope = json.loads(self.path.read_text(encoding="utf-8"))
50
+ if envelope.get("version") != 1 or not envelope["sealed"].startswith(
51
+ "ENC:"
52
+ ):
53
+ raise ValueError("invalid envelope")
54
+ return json.loads(self._decrypt(envelope["sealed"]))
55
+ except Exception:
56
+ # Inaccessible credentials are never treated as a new installation.
57
+ raise StoreError("NATIVE_STORE_UNAVAILABLE") from None
58
+
59
+ def save(self, state: dict[str, Any]) -> None:
60
+ try:
61
+ sealed = self._encrypt(
62
+ json.dumps(state, ensure_ascii=False, separators=(",", ":"))
63
+ )
64
+ self._write(
65
+ self.path,
66
+ {"version": 1, "sealed": sealed},
67
+ mode=0o600,
68
+ fsync_parent=True,
69
+ preserve_windows_acl=True,
70
+ )
71
+ except Exception:
72
+ raise StoreError("NATIVE_STORE_WRITE_FAILED") from None
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: beeply-native
3
+ Version: 0.1.0
4
+ Summary: Native customer API adapter for Beeply; no UI or staff API
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: httpx<1,>=0.27
8
+ Provides-Extra: test
9
+ Requires-Dist: pytest<10,>=8; extra == "test"
10
+ Requires-Dist: pytest-asyncio<2,>=0.24; extra == "test"
11
+ Requires-Dist: black<27,>=24; extra == "test"
12
+
13
+ # Beeply Native SDK
14
+
15
+ `beeply-native` 为 Python 3.11+ 宿主提供 Beeply 客户 API。它支持求助、消息、材料、会话续期以及邮箱绑定和恢复。宿主负责界面与安全存储。
16
+
17
+ 包在 PyPI 发布后可通过 `pip install beeply-native` 安装。仓库开发者也可用 `pip install ./clients/python` 安装本地版本。
18
+
19
+ ## 接入宿主后端
20
+
21
+ 在 Beeply 工作台打开 **设置 → 产品与渠道 → 客户端接入**,获取产品 ID 和 HTTPS API 地址。每个 API origin 和产品组合在宿主进程中持有一个客户端实例。
22
+
23
+ ```python
24
+ from beeply_native import NativeSupportClient, StateStore
25
+
26
+
27
+ def create_support(store: StateStore) -> NativeSupportClient:
28
+ return NativeSupportClient("https://api.example.com", "your-product", store)
29
+ ```
30
+
31
+ 通用宿主实现 `StateStore.load()` 和 `StateStore.save(state)`。使用宿主的加密存储保护凭据、草稿和待处理操作,并在原子写入完成后让 `save` 返回。CogineWork 宿主可用 `CogineWorkStore(api_origin, product_id)` 沿用已有的 Secret Store。UI 通过宿主 API 访问公开结果,凭据留在宿主后端。
32
+
33
+ - 已有身份用 `await client.resume()` 读取会话。用户明确发起首次求助时,调用 `await client.create_guest()`。
34
+ - 通过 `prepare_request(text)` 保存提交意图,再调用 `await client.send_operation(operation_id)`。网络结果不明时用 `await client.operation(operation_id)` 查询原操作。
35
+ - 通过 `await client.conversations()` 和 `await client.messages(conversation_id)` 读取记录。宿主确定消息可见后,调用 `await client.mark_read(conversation_id, visible_cursor)`。
36
+ - 显式退出使用 `await client.logout()`。宿主关闭时用 `await client.close()` 释放 HTTP 客户端。
37
+
38
+ SDK 以 `SupportError.code` 返回服务错误,以 `StoreError` 报告本地状态错误。恢复和重试沿用原操作 ID,验证码仅在验证时提交。
@@ -0,0 +1,7 @@
1
+ beeply_native/__init__.py,sha256=NkVtSja7i5pSZaEDfCfB88sGPONnj3kTY62sPSgLN8Q,234
2
+ beeply_native/client.py,sha256=Z6541GJsBtZ9kmhMCO-jtikldPPyU_VhL8hoorH0XUs,28223
3
+ beeply_native/store.py,sha256=efKikQ8kx7vzBirGohdLVgDIWcYRKsYDcXTBJea8Lqs,2446
4
+ beeply_native-0.1.0.dist-info/METADATA,sha256=377xaEd7AJdIIFvS2OkXx4FODdzh_UoTZNkF1S5m6Mk,2337
5
+ beeply_native-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ beeply_native-0.1.0.dist-info/top_level.txt,sha256=tpOmry3uXKCoz4_RsyfYR9H_qhHN9EXz8vPQraEEVT4,14
7
+ beeply_native-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ beeply_native