descriptor.py 4.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """CapabilityDescriptor — the relay handshake payload. EXPERIMENTAL.
  2. The connector hands one to the gateway's ``RelayAdapter`` at handshake: which
  3. platform it fronts and which capabilities to advertise to the stream consumer
  4. (char limit, draft streaming, edit/threading, markdown dialect, length unit), so
  5. one adapter serves every platform without per-platform branching. Schema evolution
  6. is additive-only, gated by ``contract_version`` (website/docs/developer-guide/relay-connector-contract.md).
  7. """
  8. from __future__ import annotations
  9. import json
  10. from dataclasses import asdict, dataclass
  11. # Bump additively (never reinterpret an existing field); a breaking change
  12. # requires updating both repos in lockstep.
  13. CONTRACT_VERSION = 1
  14. @dataclass(frozen=True)
  15. class CapabilityDescriptor:
  16. """Immutable capability profile negotiated at relay handshake (frozen: fixed for the connection)."""
  17. contract_version: int
  18. platform: str
  19. label: str
  20. max_message_length: int
  21. supports_draft_streaming: bool
  22. supports_edit: bool
  23. supports_threads: bool
  24. markdown_dialect: str
  25. len_unit: str # "chars" | "utf16"
  26. emoji: str = "\U0001f50c" # 🔌 (matches PlatformEntry default)
  27. platform_hint: str = ""
  28. pii_safe: bool = False
  29. # Optional bits default False/empty so an older connector that never sends
  30. # them reads as "not supported" — additive within contract_version 1
  31. # (from_json drops unknown keys, so newer connectors are safe against older gateways).
  32. # Connector can supply surrounding channel/group CONTEXT for an addressed turn.
  33. supports_context: bool = False
  34. # Platform can host a FLAT continuable cron surface (native Slack's
  35. # ``cron_continuable_surface: in_channel``); the scheduler fails safe to
  36. # thread mode when False (D6 gate).
  37. supports_inchannel_continuable: bool = False
  38. # Platform sender renders block-level formatting from raw markdown; when True
  39. # AND the operator enables rich_blocks/markdown_blocks, the gateway stamps
  40. # ``format_hints`` on outbound send/edit metadata.
  41. supports_block_formatting: bool = False
  42. # Outbound op names the connector implements for this platform. Empty = the
  43. # connector predates the field; callers MUST treat that as LEGACY_OPS, not
  44. # "nothing supported". Tuple keeps the frozen dataclass hashable.
  45. supported_ops: tuple = ()
  46. # Assumed capability set when a legacy connector sends no supported_ops.
  47. LEGACY_OPS = ("send", "edit", "typing", "follow_up")
  48. def supports_op(self, op: str) -> bool:
  49. """Whether the connector advertises ``op`` (legacy set when none advertised).
  50. A NEW op is therefore only True when explicitly advertised — capability
  51. can be probed without trying the op and parsing an error.
  52. """
  53. return op in (self.supported_ops or self.LEGACY_OPS)
  54. def to_json(self) -> str:
  55. """Compact, stable JSON for the handshake frame."""
  56. return json.dumps(asdict(self), sort_keys=True, ensure_ascii=False)
  57. @classmethod
  58. def from_json(cls, data: str) -> CapabilityDescriptor:
  59. """Deserialize a handshake JSON string; unknown keys ignored, missing keys default.
  60. Trust-boundary normalization (malformed input never breaks the handshake):
  61. a non-positive/garbage ``max_message_length`` ("no limit", or hostile)
  62. maps to the documented 4096 default so the adapter can always chunk;
  63. ``supported_ops`` becomes a tuple of non-empty strings, or () (legacy
  64. fallback) when malformed.
  65. """
  66. raw = json.loads(data)
  67. known = cls.__dataclass_fields__ # type: ignore[attr-defined]
  68. filtered = {k: v for k, v in raw.items() if k in known}
  69. if "max_message_length" in filtered:
  70. try:
  71. if int(filtered["max_message_length"]) <= 0:
  72. filtered["max_message_length"] = 4096
  73. except (TypeError, ValueError):
  74. filtered["max_message_length"] = 4096
  75. if "supported_ops" in filtered:
  76. raw_ops = filtered["supported_ops"]
  77. filtered["supported_ops"] = (
  78. tuple(str(op) for op in raw_ops if isinstance(op, str) and op)
  79. if isinstance(raw_ops, (list, tuple))
  80. else ()
  81. )
  82. return cls(**filtered)