medre-adapter-simplexchat 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 @@
1
+ """SimpleX Chat provider; native dependencies load only inside the owned worker."""
@@ -0,0 +1,6 @@
1
+ """Run operator commands only when invoked as a module entrypoint."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,600 @@
1
+ """Durable group ingress and explicit native local-queue handoff semantics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ from collections.abc import Callable, Mapping
8
+ from dataclasses import replace
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from medre.core.contracts.adapter import (
13
+ AdapterCapabilities,
14
+ AdapterContext,
15
+ AdapterContract,
16
+ AdapterHandoffResult,
17
+ AdapterInfo,
18
+ AdapterPermanentError,
19
+ AdapterRole,
20
+ AdapterSendError,
21
+ )
22
+ from medre.core.ingress import IngressProvenance
23
+ from medre.core.rendering.renderer import RenderingResult
24
+ from medre.core.supervision.diagnostic_contract import COMMON_DIAGNOSTIC_KEYS
25
+
26
+ from .codec import SimplexChatCodec, chat_channel
27
+ from .config import SimplexChatConfig, plain_text
28
+ from .session import SessionError, SessionUnavailable, SimplexChatSession
29
+ from .state import HandoffLedger, InboxLedger
30
+
31
+ CAPABILITIES = AdapterCapabilities(
32
+ text=True,
33
+ replies="native",
34
+ threads="fallback",
35
+ reactions="unsupported",
36
+ edits="unsupported",
37
+ deletes="unsupported",
38
+ attachments=False,
39
+ metadata_fields=False,
40
+ store_and_forward=True,
41
+ direct_messages=True,
42
+ channels=True,
43
+ identity_encryption=True,
44
+ presence=False,
45
+ topic_rooms=True,
46
+ )
47
+
48
+
49
+ def validate_payload(
50
+ result: RenderingResult, config: SimplexChatConfig
51
+ ) -> tuple[str, int, str, str | None, str | None]:
52
+ payload = result.payload
53
+ if result.target_adapter != config.adapter_id or not isinstance(payload, Mapping):
54
+ raise AdapterPermanentError("Invalid SimpleX delivery target")
55
+ try:
56
+ kind, number = config.destination(result.target_channel)
57
+ except ValueError:
58
+ raise AdapterPermanentError("Unconfigured SimpleX conversation") from None
59
+ text = payload.get("text")
60
+ if (
61
+ not {"chat_type", "chat_id", "text"} <= set(payload)
62
+ or set(payload)
63
+ - {"chat_type", "chat_id", "text", "reply_native_ref", "reply_fallback_text"}
64
+ or payload["chat_type"] != kind
65
+ or type(payload["chat_id"]) is not int
66
+ or payload["chat_id"] != number
67
+ or not plain_text(text)
68
+ or not text.strip()
69
+ or len(text.encode()) > config.max_text_bytes
70
+ ):
71
+ raise AdapterPermanentError("Invalid SimpleX addressing or rendered text")
72
+ reply_ref = payload.get("reply_native_ref")
73
+ reply_fallback = payload.get("reply_fallback_text")
74
+ if (reply_ref is None) != (reply_fallback is None):
75
+ raise AdapterPermanentError("SimpleX reply target and fallback must be paired")
76
+ if reply_ref is not None and (
77
+ not plain_text(reply_ref)
78
+ or not reply_ref
79
+ or not plain_text(reply_fallback)
80
+ or not reply_fallback.strip()
81
+ or len(reply_fallback.encode("utf-8")) > config.max_text_bytes
82
+ ):
83
+ raise AdapterPermanentError("Invalid rendered SimpleX reply")
84
+ return (
85
+ kind,
86
+ number,
87
+ text,
88
+ reply_ref if isinstance(reply_ref, str) else None,
89
+ reply_fallback if isinstance(reply_fallback, str) else None,
90
+ )
91
+
92
+
93
+ class SimplexChatAdapter(AdapterContract):
94
+ platform = "simplexchat"
95
+ role = AdapterRole.HYBRID
96
+
97
+ def __init__(
98
+ self,
99
+ config: SimplexChatConfig,
100
+ *,
101
+ session_factory: Callable[[SimplexChatConfig], SimplexChatSession] = (
102
+ SimplexChatSession
103
+ ),
104
+ ) -> None:
105
+ super().__init__()
106
+ self.config = config.validate()
107
+ self.adapter_id = config.adapter_id
108
+ self._capabilities = replace(CAPABILITIES, max_text_bytes=config.max_text_bytes)
109
+ self.ctx: AdapterContext | None = None
110
+ self.session: SimplexChatSession | None = None
111
+ self.codec: SimplexChatCodec | None = None
112
+ self.ledger: HandoffLedger | None = None
113
+ self.session_factory: Callable[[SimplexChatConfig], SimplexChatSession] = (
114
+ session_factory
115
+ )
116
+ self.task: asyncio.Task[None] | None = None
117
+ self.channels = set(config.chats)
118
+ self.inbox: InboxLedger | None = None
119
+ self.state = "unknown"
120
+ self._health_epoch = 0
121
+ self._health_active = False
122
+ self._reported_health: str | None = None
123
+ self.admission_failures = 0
124
+
125
+ async def start(self, ctx: AdapterContext) -> None:
126
+ if self.session is not None:
127
+ raise RuntimeError("SimpleX adapter is started")
128
+ if (
129
+ not self.config.database_prefix
130
+ or not self.config.state_dir
131
+ or not self.config.chats
132
+ ):
133
+ raise AdapterPermanentError(
134
+ "Configure a SimpleX profile, state directory, and conversations"
135
+ )
136
+ load = ctx.load_checkpoint
137
+ if ctx.admit_inbound is None or load is None or ctx.commit_checkpoint is None:
138
+ raise AdapterPermanentError(
139
+ "SimpleX requires durable admission and checkpoint callbacks"
140
+ )
141
+ if not await asyncio.to_thread(
142
+ Path(self.config.database_prefix + "_chat.db").is_file
143
+ ):
144
+ raise AdapterPermanentError(
145
+ "SimpleX profile is missing; run medre adapter simplexchat init explicitly"
146
+ )
147
+ if ctx.adapter_id != self.adapter_id:
148
+ raise AdapterPermanentError("SimpleX context adapter identity differs")
149
+ self._health_epoch += 1
150
+ health_epoch = self._health_epoch
151
+ self._health_active = False
152
+ self._reported_health = None
153
+ self.ctx = ctx
154
+ self._mark_started(ctx)
155
+ self._set_state("starting")
156
+ session = self.session_factory(self.config)
157
+ self.session = session
158
+ try:
159
+ await session.start()
160
+ lease = session.lease
161
+ if lease is None:
162
+ raise SessionError("SimpleX profile lease is unavailable")
163
+ self.codec = SimplexChatCodec(self.config, lease.namespace)
164
+ self.ledger = HandoffLedger(Path(self.config.state_dir) / "handoffs.sqlite")
165
+ self.inbox = InboxLedger(
166
+ Path(self.config.state_dir) / "inbox.sqlite", self.codec.profile
167
+ )
168
+ inbox = self.inbox
169
+ for channel in self.config.chats:
170
+ checkpoint = await load(self._stream(channel))
171
+ initialized = inbox.initialized(channel)
172
+ if checkpoint is not None:
173
+ metadata = json.loads(checkpoint.metadata_json)
174
+ if (
175
+ metadata
176
+ != {"profile_id": self.codec.profile, "mode": "retained_ids_v1"}
177
+ or checkpoint.cursor != "initialized"
178
+ or not initialized
179
+ ):
180
+ raise AdapterPermanentError(
181
+ "SimpleX checkpoint or inbox differs from the native profile"
182
+ )
183
+ # The official secondary controller enables history queries
184
+ # without subscribing chats. Retained IDs also deduplicate any
185
+ # native events interleaved with timestamp-ordered pagination.
186
+ before: int | None = None
187
+ anchors: set[int] = set()
188
+ missed_pages: list[int | None] = []
189
+ while True:
190
+ info, rows = await self._history(channel, before)
191
+ self._validate_conversation(info, channel)
192
+ if initialized:
193
+ # Native history is chronological within a page, but
194
+ # pagination returns newest pages first. Preserve the
195
+ # cross-page order of recovered admissions.
196
+ missed = [
197
+ row
198
+ for row in rows
199
+ if not inbox.contains(channel, row["meta"]["itemId"])
200
+ ]
201
+ if missed:
202
+ missed_pages.append(before)
203
+ else:
204
+ # On first use the existing history is a baseline, not
205
+ # an ingress replay. Batch its durable ID writes.
206
+ inbox.admitted_many(
207
+ channel, [row["meta"]["itemId"] for row in rows]
208
+ )
209
+ if len(rows) < 64:
210
+ break
211
+ before = rows[0]["meta"]["itemId"]
212
+ if before in anchors:
213
+ raise AdapterPermanentError(
214
+ "SimpleX history pagination did not advance"
215
+ )
216
+ anchors.add(before)
217
+ # Do not stop at a fully retained page: backdated events may
218
+ # exist in older pages with higher native IDs.
219
+ for anchor in reversed(missed_pages):
220
+ # Retain only page anchors, not the entire offline payload
221
+ # history. Re-read one bounded page for oldest-first ingress.
222
+ page_info, missed = await self._history(channel, anchor)
223
+ self._validate_conversation(page_info, channel)
224
+ admitted = []
225
+ for row in missed:
226
+ item_id = await self._ingest(
227
+ page_info, row, "recovered", checkpoint=False
228
+ )
229
+ if item_id is not None:
230
+ admitted.append(item_id)
231
+ inbox.admitted_many(channel, admitted)
232
+ inbox.initialize(channel)
233
+ await self._checkpoint(channel)
234
+ await session.call("start")
235
+ self._health_active = True
236
+ self._set_state("healthy")
237
+ self.task = asyncio.create_task(self._run())
238
+ self.task.add_done_callback(
239
+ lambda task: self._native_task_done(task, health_epoch)
240
+ )
241
+ except BaseException:
242
+ await self.stop()
243
+ self._set_state("failed")
244
+ raise
245
+
246
+ def _stream(self, channel: str) -> str:
247
+ return f"simplexchat:{self.config.user_id}:{channel}"
248
+
249
+ async def _checkpoint(self, channel: str) -> None:
250
+ ctx = self.ctx
251
+ codec = self.codec
252
+ if ctx is None or codec is None or ctx.commit_checkpoint is None:
253
+ raise AdapterPermanentError("SimpleX checkpoints are unavailable")
254
+ await ctx.commit_checkpoint(
255
+ self._stream(channel),
256
+ "initialized",
257
+ json.dumps({"profile_id": codec.profile, "mode": "retained_ids_v1"}),
258
+ )
259
+
260
+ def _validate_conversation(self, info: Mapping[str, Any], channel: str) -> None:
261
+ if chat_channel(info) != channel:
262
+ raise AdapterPermanentError(
263
+ "SimpleX history returned a different conversation"
264
+ )
265
+ if info["type"] == "group":
266
+ group = info["groupInfo"]
267
+ membership = group.get("membership")
268
+ scope = info.get("groupChatScope")
269
+ if (
270
+ not isinstance(membership, Mapping)
271
+ or membership.get("memberStatus")
272
+ not in {
273
+ "creator",
274
+ "connected",
275
+ "complete",
276
+ }
277
+ or (
278
+ scope is not None
279
+ and (not isinstance(scope, Mapping) or scope.get("type") != "main")
280
+ )
281
+ ):
282
+ raise AdapterPermanentError(
283
+ "SimpleX requires an active ordinary group conversation"
284
+ )
285
+ elif (
286
+ info["contact"].get("chatDeleted")
287
+ or info["contact"].get("contactStatus") != "active"
288
+ ):
289
+ raise AdapterPermanentError("SimpleX contact is not active")
290
+
291
+ async def _history(
292
+ self, channel: str, before: int | None, *, count: int = 64
293
+ ) -> tuple[Mapping[str, Any], list[Mapping[str, Any]]]:
294
+ kind, number = self.config.destination(channel)
295
+ session = self.session
296
+ if session is None:
297
+ raise SessionError("SimpleX session is unavailable")
298
+ result = await session.call(
299
+ "history", chat_type=kind, chat_id=number, before=before, count=count
300
+ )
301
+ if (
302
+ not isinstance(result, Mapping)
303
+ or not isinstance(result.get("chatInfo"), Mapping)
304
+ or not isinstance(result.get("chatItems"), list)
305
+ ):
306
+ raise AdapterPermanentError("Malformed SimpleX history response")
307
+ # Every surviving row is a Mapping: the ID validation below rejects
308
+ # any page whose row count diverges from the Mapping-filtered IDs.
309
+ rows: list[Mapping[str, Any]] = result["chatItems"]
310
+ ids = [
311
+ (
312
+ row["meta"].get("itemId")
313
+ if isinstance(row.get("meta"), Mapping)
314
+ else None
315
+ )
316
+ for row in rows
317
+ if isinstance(row, Mapping)
318
+ ]
319
+ if (
320
+ len(ids) != len(rows)
321
+ or any(type(number) is not int or number <= 0 for number in ids)
322
+ or len(set(ids)) != len(ids)
323
+ or len(rows) > count
324
+ ):
325
+ raise AdapterPermanentError("Malformed SimpleX history item IDs")
326
+ chat_info: Mapping[str, Any] = result["chatInfo"]
327
+ return chat_info, rows
328
+
329
+ async def _ingest(
330
+ self,
331
+ info: Mapping[str, Any],
332
+ row: Mapping[str, Any],
333
+ provenance: IngressProvenance,
334
+ *,
335
+ checkpoint: bool = True,
336
+ ) -> int | None:
337
+ codec = self.codec
338
+ inbox = self.inbox
339
+ ctx = self.ctx
340
+ if codec is None or inbox is None or ctx is None or ctx.admit_inbound is None:
341
+ raise AdapterPermanentError("SimpleX ingress is not started")
342
+ channel = chat_channel(info)
343
+ if channel not in self.channels:
344
+ return None
345
+ self._validate_conversation(info, channel)
346
+ meta = row.get("meta")
347
+ item_id = meta.get("itemId") if isinstance(meta, Mapping) else None
348
+ if type(item_id) is not int or item_id <= 0:
349
+ raise AdapterPermanentError("Malformed SimpleX event item ID")
350
+ if inbox.contains(channel, item_id):
351
+ return None
352
+ if event := codec.decode(info, row):
353
+ await ctx.admit_inbound(event, provenance)
354
+ # If this write fails, core admission deduplicates the stable UUID
355
+ # on retry. No admitted ID is recorded before successful admission.
356
+ if checkpoint:
357
+ inbox.admitted(channel, item_id)
358
+ return item_id
359
+
360
+ async def _run(self) -> None:
361
+ epoch = self._health_epoch
362
+ session = self.session
363
+ if session is None:
364
+ raise SessionError("SimpleX session is unavailable")
365
+ pending: list[Any] = []
366
+ while True:
367
+ session.wake.clear()
368
+ try:
369
+ if not pending:
370
+ pending = await session.call("events")
371
+ if not isinstance(pending, list):
372
+ raise AdapterPermanentError("Malformed SimpleX event batch")
373
+ while pending:
374
+ record = pending[0]
375
+ if (
376
+ not isinstance(record, Mapping)
377
+ or not isinstance(record.get("chatInfo"), Mapping)
378
+ or not isinstance(record.get("chatItem"), Mapping)
379
+ ):
380
+ raise AdapterPermanentError("Malformed SimpleX event record")
381
+ await self._ingest(record["chatInfo"], record["chatItem"], "live")
382
+ pending.pop(0)
383
+ self._set_state("healthy", epoch=epoch)
384
+ except (SessionError, AdapterPermanentError):
385
+ self._set_state("failed", epoch=epoch)
386
+ await session.stop()
387
+ return
388
+ except asyncio.CancelledError:
389
+ if self._health_active:
390
+ self._set_state("failed", epoch=epoch)
391
+ raise
392
+ except Exception:
393
+ self.admission_failures += 1
394
+ self._set_state("degraded", epoch=epoch)
395
+ try:
396
+ await asyncio.wait_for(
397
+ session.wake.wait(), self.config.poll_interval_seconds
398
+ )
399
+ except TimeoutError:
400
+ pass
401
+
402
+ async def deliver(self, result: RenderingResult) -> AdapterHandoffResult:
403
+ kind, number, text, reply_ref, fallback_text = validate_payload(
404
+ result, self.config
405
+ )
406
+ # validate_payload admits only configured conversation channels, so
407
+ # the target is a concrete channel string from this point on.
408
+ channel = result.target_channel
409
+ if channel is None:
410
+ raise AdapterPermanentError("Unconfigured SimpleX conversation")
411
+ codec = self.codec
412
+ if (
413
+ self.state not in {"healthy", "degraded"}
414
+ or self.session is None
415
+ or self.ledger is None
416
+ or codec is None
417
+ ):
418
+ raise AdapterSendError("SimpleX adapter is not available")
419
+ provenance = result.attempt_provenance
420
+ if (
421
+ provenance is None
422
+ or provenance.target_adapter != self.adapter_id
423
+ or provenance.target_channel != result.target_channel
424
+ or provenance.event_id != result.event_id
425
+ ):
426
+ raise AdapterPermanentError(
427
+ "SimpleX requires matching delivery attempt provenance"
428
+ )
429
+ # Resolve quote scope before reserving. If the profile/user/chat no
430
+ # longer matches, freeze the readable fallback as the outgoing body.
431
+ quoted_item_id = codec.quote_item_id(channel, reply_ref) if reply_ref else None
432
+ if reply_ref and quoted_item_id is None:
433
+ assert fallback_text is not None
434
+ text, reply_ref, fallback_text = fallback_text, None, None
435
+ try:
436
+ reserved, native_id = self.ledger.reserve(
437
+ provenance,
438
+ channel,
439
+ text,
440
+ reply_ref=reply_ref,
441
+ fallback_text=fallback_text,
442
+ )
443
+ if not reserved and native_id is None:
444
+ raise ValueError(
445
+ "SimpleX handoff outcome is uncertain; inspect the native profile before retrying"
446
+ )
447
+ if reserved:
448
+ # Seal both permitted outcomes before consulting native state.
449
+ # Accepted reservations bypass this check and never send again.
450
+ if quoted_item_id is not None:
451
+ available = await self.session.call(
452
+ "quote_target",
453
+ chat_type=kind,
454
+ chat_id=number,
455
+ item_id=quoted_item_id,
456
+ )
457
+ if type(available) is not bool:
458
+ raise ValueError("Invalid native quote lookup result")
459
+ if not available:
460
+ assert fallback_text is not None
461
+ text, quoted_item_id = fallback_text, None
462
+ records = await self.session.call(
463
+ "send",
464
+ chat_type=kind,
465
+ chat_id=number,
466
+ text=text,
467
+ quoted_item_id=quoted_item_id,
468
+ )
469
+ if (
470
+ not isinstance(records, list)
471
+ or len(records) != 1
472
+ or chat_channel(records[0].get("chatInfo", {}))
473
+ != result.target_channel
474
+ ):
475
+ raise ValueError(
476
+ "SimpleX returned an unexpected native send result"
477
+ )
478
+ item = records[0].get("chatItem", {})
479
+ item_id = item.get("meta", {}).get("itemId")
480
+ if (
481
+ type(item_id) is not int
482
+ or item_id <= 0
483
+ or item.get("chatDir", {}).get("type")
484
+ != ("groupSnd" if kind == "group" else "directSnd")
485
+ or item.get("content", {}).get("type") != "sndMsgContent"
486
+ or item.get("content", {}).get("msgContent", {}).get("type")
487
+ != "text"
488
+ or item.get("content", {}).get("msgContent", {}).get("text") != text
489
+ ):
490
+ raise ValueError("SimpleX native send identity or body differs")
491
+ native_id = codec.reference(channel, item_id)
492
+ self.ledger.accepted(provenance, native_id)
493
+ except asyncio.CancelledError:
494
+ # Cancellation after reserving may have reached the native queue.
495
+ raise
496
+ except SessionUnavailable:
497
+ # call() refused before writing to the worker. A retry is safe;
498
+ # do not strand this attempt in the handoff ledger.
499
+ self.ledger.release(provenance)
500
+ raise AdapterSendError(
501
+ "SimpleX session was unavailable before send"
502
+ ) from None
503
+ except Exception:
504
+ # Rejections returned by the SDK are NOT proven unsent: the native
505
+ # API may have enqueued before reporting an error. Fail closed.
506
+ raise AdapterPermanentError(
507
+ "SimpleX handoff is uncertain or invalid; inspect the native profile before retrying"
508
+ ) from None
509
+ return AdapterHandoffResult(
510
+ native_message_id=native_id,
511
+ native_channel_id=result.target_channel,
512
+ confirmation_level="local_queue",
513
+ note=(
514
+ "Persisted in the native SimpleX queue; remote receipt is not inferred"
515
+ if reserved
516
+ else "Reused an earlier persisted native handoff; no new text was submitted"
517
+ ),
518
+ )
519
+
520
+ async def stop(self, timeout: float = 5.0) -> None:
521
+ self._health_active = False
522
+ self._health_epoch += 1
523
+ self._reported_health = None
524
+ # Even cancellation of task gathering must not readmit native sends.
525
+ self._set_state("failed")
526
+ if self.task is not None:
527
+ self.task.cancel()
528
+ await asyncio.gather(self.task, return_exceptions=True)
529
+ self.task = None
530
+ if self.session is not None:
531
+ try:
532
+ await self.session.stop()
533
+ except BaseException:
534
+ self._set_state("failed")
535
+ raise
536
+ self.session = None
537
+ if self.inbox is not None:
538
+ self.inbox.close()
539
+ self.inbox = None
540
+ if self.ledger is not None:
541
+ self.ledger.close()
542
+ self.ledger = None
543
+ self._set_state("unknown")
544
+
545
+ def _native_task_done(self, task: asyncio.Task[None], epoch: int) -> None:
546
+ """Observe unexpected native-owner exit, including cancellation before first execution."""
547
+ if not self._health_active or epoch != self._health_epoch:
548
+ return
549
+ if task.cancelled() or task.exception() is not None:
550
+ self._set_state("failed", epoch=epoch)
551
+
552
+ def _set_state(self, state: str, *, epoch: int | None = None) -> None:
553
+ """Publish existing native-owner observations without adding polling or send authority."""
554
+ if epoch is not None and epoch != self._health_epoch:
555
+ return
556
+ self.state = state
557
+ if (
558
+ not self._health_active
559
+ or self.ctx is None
560
+ or state not in {"healthy", "degraded", "failed"}
561
+ ):
562
+ return
563
+ report = getattr(self.ctx, "report_health", None)
564
+ if report is None or self._reported_health == state:
565
+ return
566
+ try:
567
+ report(self._health_info())
568
+ self._reported_health = state
569
+ except Exception as exc:
570
+ self.ctx.logger.warning(
571
+ "simplexchat health notification failed (%s)", type(exc).__name__
572
+ )
573
+
574
+ async def health_check(self) -> AdapterInfo:
575
+ """Read the native owner's retained local health without another native call."""
576
+ return self._health_info()
577
+
578
+ def _health_info(self) -> AdapterInfo:
579
+ """Use the same native-owner state for explicit probes and reports."""
580
+ return AdapterInfo(
581
+ self.adapter_id,
582
+ self.platform,
583
+ self.role,
584
+ "0.1.0",
585
+ self._capabilities,
586
+ health=self.state,
587
+ )
588
+
589
+ def diagnostics(self) -> dict[str, object]:
590
+ """Expose retained health and explicit unknowns without native I/O."""
591
+ return {
592
+ **dict.fromkeys(sorted(COMMON_DIAGNOSTIC_KEYS)),
593
+ "health": self.state,
594
+ "mode": "live",
595
+ "adapter_id": self.adapter_id,
596
+ "health_scope": "native_profile",
597
+ "peer_reachability": "not_inferred",
598
+ "configured_conversations": len(self.config.chats),
599
+ "admission_failures": self.admission_failures,
600
+ }